【问题标题】:Create new Node for Singly Linked List in Java在 Java 中为单链表创建新节点
【发布时间】:2016-12-22 00:58:48
【问题描述】:

我仍在学习 Java,目前正在解决“Cracking the Coding Interview”中的问题,第 2 章(LinkedList)中的一个问题要求从未排序的链表中删除重复项。我在 GitHub 上找到了一堆答案/解决方案,但我想创建自己的 Node,并编写自己的版本。

到目前为止,我实现的是我创建了 Node 类并编写了可以从未排序的 LinkedList 中删除重复项的函数/方法,但是当我尝试对其进行测试时,我尝试在主函数中创建 LinkedList,但是我仍然不知道如何弄清楚。有人可以帮助/指导我如何创建单链表吗? 基本上,我创建了四个节点(第四、第三、第二、头),并使用 Node 类将它们全部连接起来。

提前致谢,

public class Node {
    int data;
    Node next;

    public Node(int data, Node next){
        this.data = data;
        this.next = next;
    }

    public String toString(){
        return data + "";
    }
}


public class problem1 {

    public void Remove_duplicates(Node head){
        if(head == null){
            return;
        }

        Node current = head;
        while(current != null){
            Node runner = current;
            while(runner.next != null){
                if(runner.next.data == current.data){
                    runner.next = runner.next.next;
                }
                else {
                    runner = runner.next;
                }
            }
            current = current.next;
        }
    }

    public static void main(String[] args) {

        Node fourth = new Node(5,null);
        Node third = new Node(3,fourth);
        Node second = new Node(4,third);
        Node head = new Node(3,second);
        for(Node a: head){
            // ERROR: saying can only iterate over an array (or) java.lang.Iterable
            System.out.println(a.toString());
            a = a.next;
        }
    }
}

【问题讨论】:

  • return data + ""; 废话。试试return Integer.toString(data);
  • @bradimus 代码return data + ""; 应该可以工作。
  • 它会起作用,但“会起作用”和“好风格”不是同义词。通读this
  • String.valueOf(data‌​) 同样不错。 data + "" 没有表达明确的意图,而 String.valueOf(data‌​)Integer.toString(dat‌​a) 则表达了明确的意图。通读我喜欢的问题。一些答案/cmets 解决了这个问题以及语句的效率。
  • @bradimus 是的,一个好建议! - 但是下次最好在评论中添加一个为什么应该更改代码的原因,这样每个人都会理解它:-)

标签: java linked-list nodes


【解决方案1】:

尝试另一种循环,例如while

Node head = new Node(3, second);
Node node = head;
while (node.next != null) {
    System.out.println(node.toString());
    node = node.next;
}

就像它解释的那样,它不知道如何迭代您的节点。 使用foreach 的另一种方法是创建一个自己的类,该类实现接口Iterable 并包含您的LinkedList 逻辑。

对于第二种方法,我建议您阅读以下内容:How can I implement the Iterable interface?

【讨论】:

  • 感谢您的反馈。我没有意识到我需要创建一个自己的类来使用 foreach 循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多