Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active June 3, 2017 15:05
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 anil477/05906ad3b2e295c60122b5d2a7651443 to your computer and use it in GitHub Desktop.
Save anil477/05906ad3b2e295c60122b5d2a7651443 to your computer and use it in GitHub Desktop.
Sort a linked list of 0,1 and 2's - count 0, 1 and 2's.
// So we create there list, one each for 0, 1 and 2.
// The head of each of these point to the 0, 1 and 2, node in the main list given.
// while travesing we point head0 to first node with 0, the next of which points to next node with 0 and it goes on.
// similarly for 1 and 2.
// in the end we add head2 at end of head1. n then add head1 to end of head0.
// ignore the crappy naming convention. It's jsut a POC that it can be done this way. GeeksForGeek does not has this solution
class Node {
int data;
Node next;
Node(int d)
{
data = d;
next = null;
}
}
class LinkedList
{
Node head; // head of list
/* This function prints contents of linked list starting from head */
public void printList()
{
Node temp = head;
System.out.println( " Print Function: ");
while (temp != null)
{
System.out.println("Data: " + temp.data);
temp = temp.next;
}
System.out.println();
}
public void create()
{
Node head0 = null;
Node head1 = null;
Node head2 = null;
Node f = null;
Node node0 = null;
Node node1 = null;
Node node2 = null;
Node temp = this.head;
while (temp!=null)
{
if (temp.data == 0)
{
if(head0 == null)
{
node0 = new Node(0);
head0 = node0;
node0.next = null;
}
else
{
node0 = new Node(0);
f = head0;
while(f.next!=null)
{
f = f.next;
}
f.next = node0;
}
}
else if(temp.data == 1)
{
if(head1 == null)
{
node1 = new Node(1);
head1 = node1;
node1.next = null;
}
else
{
node1 = new Node(1);
f = head1;
while(f.next!=null)
{
f = f.next;
}
f.next = node1;
}
}
else if(temp.data == 2)
{
if(head2 == null)
{
node2 = new Node(2);
head2 = node2;
node2.next = null;
}
else
{
node2 = new Node(2);
f = head2;
while(f.next!=null)
{
f = f.next;
}
f.next = node2;
}
}
temp = temp.next;
}
Node loop0 = head0;
while(loop0.next!=null)
{
loop0 = loop0.next;
}
loop0.next = head1;
loop0 = head0;
while(loop0.next!=null)
{
loop0 = loop0.next;
}
loop0.next = head2;
loop0 = head0;
while(loop0!=null)
{
System.out.println(loop0.data);
loop0 = loop0.next;
}
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.head = new Node(0);
Node second = new Node(2);
Node third = new Node(1);
Node fourth = new Node(2);
Node fifth = new Node(2);
llist.head.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
llist.printList();
llist.create();
}
public void addAtHead(int data)
{
Node node = new Node(data);
node.next = this.head;
this.head = node;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment