当我尝试实现一种删除重复项的方法时,它会返回链接列表,并且重复项仍在其中。我不确定这是变量分配问题还是潜在的我创建的show()方法。
https://www.dropbox.com/s/2cjj4nb4v8i5fg9/RemoveDuplicates.zip?dl=0
public class LinkedList {
LinkedListNode head;
//generating add method to
public void add(int data) {
LinkedListNode newNode = new LinkedListNode();
newNode.data = data;
newNode.next = null;
if (head == null) {
head = newNode;
}
else {
LinkedListNode current = head;
while(current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void show() {
LinkedListNode newNode = head;
while(newNode.next != null) {
System.out.println(newNode.data);
newNode = newNode.next;
}
System.out.println(newNode.data);
}
}
public class Test {
public static void main(String[] args) {
LinkedListNode head = new LinkedListNode();
//12 and 5 are duplicates
LinkedList list = new LinkedList();
list.add(5);
list.add(45);
list.add(12);
list.add(12);
list.add(5);
list.add(33);
list.add(12);
list.add(45);
list.show();
removeDuplicates(head);
list.show();
}
public static void removeDuplicates(LinkedListNode head) {
LinkedListNode current = head;
LinkedListNode runner = null;
while (current != null) {
runner = current;
while (runner.next != null) {
if (runner.next.data == current.data) {
runner.next = runner.next.next;
}
else {
runner = runner.next;
}
}
current = current.next;
}
}
}
答案 0 :(得分:2)
您主要方法中的head
与链表中的head
不同。
main方法中的head
始终为空,并且根本没有修改list
。