Removing Duplicates:
/**
* Remove duplicates without using a buffer.
*
* @param head
*/
public static void removeUnsortedDuplicatesWithoutBuffer(final LinkedListNode head) {
//if the linked list is empty
if(head == null) {
throw new RuntimeException("linked list is empty");
//return;
}
LinkedListNode current = head;
LinkedListNode runner = null ;
LinkedListNode previous = null ;
boolean flag = false ;
while(current != null) {
runner = head;
while(runner != current) {
if(current.getData() != runner.getData()) {
runner = runner.getNext();
flag = false;
} else {
previous.setNext(current.getNext());
current = previous.getNext();
flag = true;
break;
}
}
if(!flag) {
previous = current;
current = current.getNext();
}
}
}
LinkedListNode:
class LinkedListNode {
private int data;
private LinkedListNode next ;
public LinkedListNode(final int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public LinkedListNode getNext() {
return next;
}
public void setNext(LinkedListNode next) {
this.next = next;
}
public void appendAtTail(final int data) {
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = this;
while(current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
Test Case:
@Test
public void testRemoveDuplicatesFromUnsortedSortedLL() {
LinkedListNode head = new LinkedListNode(30);
head.appendAtTail(20);
head.appendAtTail(20);
head.appendAtTail(30);
head.appendAtTail(10);
head.appendAtTail(50);
head.appendAtTail(10);
head.appendAtTail(10);
head.appendAtTail(20);
head.appendAtTail(50);
head.appendAtTail(50);
head.appendAtTail(100);
RemoveDuplicates.removeUnsortedDuplicatesWithoutBuffer(head);
}
I wrote this code recently to remove duplicates from linked list without using buffer and was trying to analyze its complexity : Time taken for traversing is O(n) For each operation we need to move runner node n times to remove duplicates Total Complexity : O(n2). Is this correct ?? I guess not because this is no better than using two for loops and comparing each element with the rest of the elements in the LinkedList . What am I doing wrong here?