You are given a linked list consisting of just 0s, 1s and 2s. You need to return
Fantastic news! We've Found the answer you've been seeking!
Question:
Input Format:
The input contains the number of elements in the linked list, followed by the elements in the linked list.
Output Format:
The output contains the sorted linked list.
Sample Test Cases:
Input:
5 1 0 2 1 0
Output:
0 0 1 1 2
Input:
8 0 1 2 0 2 1 0 2
Output:
0 0 0 1 1 2 2 2
import java.util.Scanner; class LinkedList { Node head; class Node { int data; Node next; Node(int d) {data = d; next = null; } } void sortList() { //Write the code here to complete } public void push(int new_data) { Node new_node = new Node(new_data); new_node.next = head; head = new_node; } void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } } class Source { public static void main(String args[]) { int n; Scanner s = new Scanner(System.in); n = s.nextInt(); LinkedList li = new LinkedList(); for(int i = 0; i < n; i++) { int a; a = s.nextInt(); li.push(a); } li.sortList(); li.printList(); } }
Related Book For
Introduction to Algorithms
ISBN: 978-0262033848
3rd edition
Authors: Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest
Posted Date: