我仍在学习 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;
}
}
}
尝试另一种循环,例如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
logic.
对于第二种方法,我建议您阅读以下内容:如何实现 Iterable 接口? https://stackoverflow.com/questions/601658/how-can-i-implement-the-iterable-interface
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)