原文:
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?
译文:
从一个未排序的链表中移除重复的项
进一步地,
如果不允许使用临时的缓存,你如何解决这个问题?
首先定义一个node类
public class LinkedListNode {
int data;
LinkedListNode next;
public LinkedListNode(int data) {
this.data = data;
this.next = null;
}
}
1,允许使用临时的缓存,使用一个哈希表,如果遇到没有遇到过的元素写入哈希表,如果遇到的是重复的,删除。
public static void main(String args[]) {
LinkedListNode head = null;
LinkedListNode tmp = null;
int a[] = {1, 2, 3, 3, 2, 1, 4};
for (int i = 0; i < a.length; i++) {
LinkedListNode next = new LinkedListNode(a[i]);
if (i == 0) {
head = tmp = next;
continue;
}
tmp.next = next;
tmp = next;
}
// Print the list(before)
tmp = head;
while (tmp != null) {
System.out.println(tmp.data);
tmp = tmp.next;
};
delDup1(head);
// Print the list(after)
while (head != null) {
System.out.println(head.data);
head = head.next;
};
}
public static void delDup1(LinkedListNode head) {
LinkedListNode n = head;
Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>();
LinkedListNode previous = null;
while (n != null) {
if (table.containsKey(new Integer(n.data))) {
previous.next = n.next;
} else {
table.put(new Integer(n.data), new Integer(1));
previous = n;
}
n = n.next;
}
}
2,不允许使用临时的缓存
public static void main(String args[]) {
LinkedListNode head = null;
LinkedListNode tmp = null;
int a[] = {1, 2, 3, 3, 2, 1, 4};
for (int i = 0; i < a.length; i++) {
LinkedListNode next = new LinkedListNode(a[i]);
if (i == 0) {
head = tmp = next;
continue;
}
tmp.next = next;
tmp = next;
}
// Print the list(before)
tmp = head;
while (tmp != null) {
System.out.println(tmp.data);
tmp = tmp.next;
};
delDup(head);
// Print the list(after)
while (head != null) {
System.out.println(head.data);
head = head.next;
};
}
public static void delDup(LinkedListNode head) {
if (head == null) {
return;
}
LinkedListNode runner = head;
LinkedListNode runnernext = head;
LinkedListNode current = head;
while (current != null) {
runner = current;
runnernext = current.next;
int currentData = current.data;
while (runnernext != null) {
if (runnernext.data == currentData) {
runner.next = runnernext.next;
runnernext = runner.next;
} else {
runner = runnernext;
runnernext = runner.next;
}
}
current = current.next;
}
}