2.1 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?
RemoveDuplicate1()使用了Java的Hashtable,如果发现了duplicate,直接修改前继的next。
RemoveDuplicate2()没有使用buffer,方法类似1.3。
package Question2_1;
import java.util.Hashtable;
public class Question2_1<AnyType>
{
public static void main(String[] args)
{
Question2_1<Integer> q = new Question2_1<Integer>();
q.AddToList(4);q.AddToList(5);q.AddToList(6);q.AddToList(7);
q.AddToList(1);q.AddToList(0);q.AddToList(1);q.AddToList(8);
q.AddToList(3);q.AddToList(2);q.AddToList(5);q.AddToList(4);
q.PrintList();
q.RemoveDuplicate2();
q.PrintList();
}
private Node<AnyType> head;
public Question2_1()
{
// Initialize head to be an empty node
head = new Node<AnyType>(null, null);
}
public void AddToList(AnyType e)
{
Node<AnyType> temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = new Node<AnyType>(e, null);
}
public void RemoveDuplicate1()
{
Hashtable<AnyType, Boolean> hashtable = new Hashtable<AnyType, Boolean>();
Node<AnyType> pre = head;
Node<AnyType> cur = head.next;
while (cur != null)
{
// If find a duplicate, bypass current node
if (hashtable.containsKey(cur.data))
pre.next = cur.next;
else
{
// If no duplicate, add current node data to hash table, and then modify pointer
hashtable.put(cur.data, true);
pre = cur;
}
cur = cur.next;
}
}
public void RemoveDuplicate2()
{
Node<AnyType> pre = head;
Node<AnyType> cur = head.next;
while (cur != null)
{
// Use a temporary Node to iterate all prior nodes
Node<AnyType> temp = head;
for (; temp.next != cur; temp = temp.next)
if (temp.data == cur.data)
break;
// If temp.next doesn't equal to cur; then we find a duplicate, bypass current node
if (temp.next != cur)
pre.next = cur.next;
else
pre = cur;
cur = cur.next;
}
}
public void PrintList()
{
Node<AnyType> temp = head;
while (temp.next != null)
{
temp = temp.next;
System.out.print(temp.data + " ");
}
System.out.println();
}
private class Node<Type>
{
Node(Type d, Node<Type> n)
{
data = d;
next = n;
}
Type data;
Node<Type> next;
}
}