java - 在Java中为单链表创建新节点

标签 java linked-list nodes

我仍在学习 Java,目前正在解决《破解编码面试》中的问题,第 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;
        }
    }
}

最佳答案

尝试另一种循环,例如同时

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

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

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

关于java - 在Java中为单链表创建新节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38961553/

相关文章:

c - 警告 : extra tokens at end of#include directive

java - 从类路径获取文件,以便测试可以在所有机器上运行

java - java3d Vector4f 和 Vector3f 之间的区别

java - LinkedList队列实现

c++ - 有没有更好的方法来实现try..catch机制?

javascript - 如何使用XML文档的childNodes?

c++ - 节点之间的存储成本

c++ - Append 在 C++ 中的数组链接列表中不起作用

java - 每个用户的队列 - Appengine Java - 设计建议

java - 使用 UploadObjectSingleOperation 示例将文件上传到 aws s3 时出现 SecurityException