Skip to content

Instantly share code, notes, and snippets.

@kmdarshan
Created August 26, 2013 00:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmdarshan/6337103 to your computer and use it in GitHub Desktop.
Save kmdarshan/6337103 to your computer and use it in GitHub Desktop.
Removing duplicates in a linked list. Comparison using different methods.
package linkedlist;
import java.util.HashSet;
import java.util.Iterator;
class Node {
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
}
public class testlinkedlist {
public Node add(int data, Node head){
if(head == null){
return head = new Node(data);
}
Node temp = head;
while(temp.next != null){
temp = temp.next;
}
temp.next = new Node(data);
return head;
}
public void display(Node head){
while(head != null){
System.out.println(head.data);
head = head.next;
}
}
public boolean containsLoop(Node head){
Node p1, p2;
p1 = p2 = head;
do {
p1 = p1.next;
p2 = p2.next.next;
} while (p1 != p2);
if(p1 == p2) return true;
return false;
}
public Node removeDuplicate(Node head){
Node p1, p2;
p1 = head;
while(p1 != null){
p2 = p1.next;
Node prev = p1;
while(p2 != null){
if(p1.data == p2.data){
// there is a duplicate here
// change the previous data to next
prev.next = p2.next;
}
prev = p2;
p2 = p2.next;
}
p1 = p1.next;
}
return head;
}
public Node removeDupsUsingList(Node head) {
Node head2 = null;
HashSet<Integer> set = new HashSet<Integer>();
Node temp = head;
while(temp != null){
set.add(temp.data);
temp = temp.next;
}
testlinkedlist tt = new testlinkedlist();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
head2 = tt.add(integer, head2);
}
return head2;
}
/**
* @param args
*/
public static void main(String[] args) {
long starttime1 = System.nanoTime();
Node head = null;
testlinkedlist tt = new testlinkedlist();
head = tt.add(145, head);
head = tt.add(451, head);
head = tt.add(452, head);
head = tt.add(425, head);
head = tt.add(145, head);
/**
* toggle below for finding the runtimes
*/
head = tt.removeDuplicate(head);
head = tt.removeDupsUsingList(head);
tt.display(head);
long estimatedTime1 = System.nanoTime() - starttime1;
System.out.println(estimatedTime1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment