Sort Linked List containing values from 1 to N | Java program to sort linked list containing values from 1 to N ; Link list node ; Function to sort linked list ; Function to add a node at the beginning of Linked List ; allocate node ; put in the data ; link the old list off the new node ; move the head to point to the new node ; This function prints contents of linked list starting from the given node ; Driver Code ; The constructed linked list is : 3 -> 5 -> 4 -> 6 -> 1 -> 2
import java . util . * ; class GFG { static class Node { int data ; Node next ; } ; static Node start ; static void sortList ( Node head ) { int startVal = 1 ; while ( head != null ) { head . data = startVal ; startVal ++ ; head = head . next ; } } static void push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . next = head_ref ; head_ref = new_node ; start = head_ref ; } static void printList ( Node node ) { while ( node != null ) { System . out . print ( node . data + " ▁ " ) ; node = node . next ; } } public static void main ( String [ ] args ) { start = null ; push ( start , 2 ) ; push ( start , 1 ) ; push ( start , 6 ) ; push ( start , 4 ) ; push ( start , 5 ) ; push ( start , 3 ) ; sortList ( start ) ; printList ( start ) ; } }