text: Sort Linked List containing values from 1 to N | C ++ program to sort linked list containing values from 1 to N ; A linked 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 program to test above function ; The constructed linked list is : 3 -> 5 -> 4 -> 6 -> 1 -> 2
code: #include <iostream> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool sortList ( struct Node * head ) { int startVal = 1 ; while ( head != NULL ) { head -> data = startVal ; startVal ++ ; head = head -> next ; } } void push ( struct Node * * head_ref , int new_data ) { struct Node * new_node = ( struct Node * ) malloc ( sizeof ( struct Node ) ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } void printList ( struct Node * node ) { while ( node != NULL ) { cout << node -> data << " ▁ " ; node = node -> next ; } } int main ( ) { struct Node * start = NULL ; push ( & start , 2 ) ; push ( & start , 1 ) ; push ( & start , 6 ) ; push ( & start , 4 ) ; push ( & start , 5 ) ; push ( & start , 3 ) ; sortList ( start ) ; printList ( start ) ; return 0 ; }