Answered step by step
Verified Expert Solution
Question
1 Approved Answer
You are given a linked list consisting of just 0s, 1s and 2s. You need to return the sorted linked list. Code structure is already
You are given a linked list consisting of just 0s, 1s and 2s. You need to return the sorted linked list. Code structure is already given, you need to add the remaining code to finish it.
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(); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
To sort the given linked list consisting of 0s 1s and 2s you can use the Dutch National Flag algorit...Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started