【发布时间】: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(data)则表达了明确的意图。通读我喜欢的问题。一些答案/cmets 解决了这个问题以及语句的效率。 -
@bradimus 是的,一个好建议! - 但是下次最好在评论中添加一个为什么应该更改代码的原因,这样每个人都会理解它:-)
标签: java linked-list nodes