Skip to content

Instantly share code, notes, and snippets.

@astkaasa
Last active December 15, 2015 01:59
Show Gist options
  • Save astkaasa/5184080 to your computer and use it in GitHub Desktop.
Save astkaasa/5184080 to your computer and use it in GitHub Desktop.
import java.util.HashSet;
import java.util.Set;
public class FindDuplicateLL {
public static void main( String[] args ) {
LinkNode head = new LinkNode( 1 );
head.append( new LinkNode( 2 ) );
head.append( new LinkNode( 3 ) );
head.append( new LinkNode( 1 ) );
head.append( new LinkNode( 5 ) );
printLinkedList( head );
removeDuplicateNodeNoBuffer( head );
System.out.println( head.getValue() );
printLinkedList( head );
}
public static void printLinkedList( LinkNode head ) {
while ( head != null ) {
System.out.print( head.getValue() );
System.out.print( "->" );
head = head.getNext();
}
System.out.println( "null" );
}
public static void removeDuplicateNode( LinkNode head ) {
HashSet<Integer> set = new HashSet<>();
LinkNode p = null;
while ( head != null ) {
if ( set.contains( head.getValue() ) )
p.setNext( head.getNext() );
else {
p = head;
set.add( head.getValue() );
}
head = head.getNext();
}
}
public static void removeDuplicateNodeNoBuffer( LinkNode head ) {
if ( head == null )
return;
LinkNode p1 = head;
while ( p1!= null ) {
LinkNode p2 = p1;
while ( p2.getNext() != null ) {
if ( p2.getNext().getValue() != p1.getValue() )
p2 = p2.getNext();
else p2.setNext( p2.getNext().getNext() );
}
p1 = p1.getNext();
}
}
}
public class LinkNode {
private int value;
private LinkNode next;
public LinkNode( int val ) {
this.value = val;
this.next = null;
}
public int getValue() {
return value;
}
public void setValue( int value ) {
this.value = value;
}
public LinkNode getNext() {
return next;
}
public void setNext( LinkNode n ) {
this.next = n;
}
public void append( LinkNode n ) {
LinkNode currNode = this;
while ( currNode.next != null ) {
currNode = currNode.next;
}
currNode.next = n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment