gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:59:53 25 4
gpt4 key购买 nike

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

到目前为止我已经实现的是我创建了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com