Sunday, 24 April 2016

Sorting a Linked List contains only 0's,1's and 2's using Java ...

Problem - Given an unsorted Linked List containing values from the set {0,1,2}                       only sort it using java. 

Here is the code ....


       

public class SortLinkedList {

 public static void main(String[] args) {

  LinkedList list = new LinkedList();
  list.push(0);
  list.push(1);
  list.push(0);
  list.push(1);
  list.push(2);
  list.push(2);
  list.push(0);
  list.push(1);
  list.push(1);
  list.push(2);
  list.push(0);

  System.out.println("Before sorting");
  list.printList();
  System.out.println();
  list.sortList();
  System.out.println("After sorting");
  list.printList();
 }

}
class LinkedList {

 private Node head;

 class Node {
  int data;
  Node next;
  Node(int d) {
   next = null;
   data = d;
  }
 }

 public void push(int d) {

  Node new_Node = new Node(d);

  new_Node.next = head;
  head = new_Node; //Adding elements at the start of linked list
 }

 public void printList() {
  Node temp = head;
  while (temp != null) {
   System.out.print(temp.data);
   temp = temp.next;
   System.out.print(" ");
  }
 }
 public void sortList() {
  int[] count = new int[3];
  count[0] = 0;
  count[1] = 0;
  count[2] = 0;
  Node temp = head;
  while (temp != null) {
   if (temp.data == 0)
    count[0]++;
   else if (temp.data == 1)
    count[1]++;
   else count[2]++;
   temp = temp.next;
  }
  temp = head;
  int i = 0;
  while (temp != null) {
   if (count[i] == 0)
    i++;
   else {
    temp.data = i;
    temp = temp.next;
    count[i]--;
   }
  }
 }
}

       
 

No comments:

Post a Comment