public class RemoveDuplicatesFromLinkedList {
public static void main(String[] args) {
Node head = new Node(0);
append(1, head);
append(2, head);
append(2, head);
append(3, head);
append(4, head);
append(4, head);
append(4, head);
append(5, head);
append(5, head);
append(1, head);
System.out.println("input");
printLinkedList(head);
removeDuplicates(head);
System.out.println("output");
printLinkedList(head);
}
public static void printLinkedList(Node head) {
Node tempHead = head;
while (tempHead != null) {
System.out.println(tempHead.data);
tempHead = tempHead.next;
}
}
public static void append(int item, Node head) {
Node newNode = new Node(item);
if (head == null) {
head = newNode;
return;
}
Node tempHead = head;
while (tempHead.next != null) {
tempHead = tempHead.next;
}
tempHead.next = newNode;
}
public static void removeDuplicates(Node head) {
if (head == null)
return;
Node previous = head;
Node current = previous.next;
while (current != null) {
Node runner = head;
while (runner != current) { // Check for earlier dups
if (runner.data == current.data) {
Node tmp = current.next; // remove current
previous.next = tmp;
current = tmp; // update current to next node
break; // all other dups have already been removed
}
runner = runner.next;
}
if (runner == current) { // current not updated - update now
previous = current;
current = current.next;
}
}
}
}
No comments:
Post a Comment