Sort Linked List containing values from 1 to N | Python3 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 po to the new node ; This function prs contents of linked list starting from the given node ; Driver Code ; The constructed linked list is : 3.5 . 4.6 .1 . 2
import math NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT def sortList ( head ) : NEW_LINE INDENT startVal = 1 NEW_LINE while ( head != None ) : NEW_LINE INDENT head . data = startVal NEW_LINE startVal = startVal + 1 NEW_LINE head = head . next NEW_LINE DEDENT DEDENT def push ( head_ref , new_data ) : NEW_LINE INDENT new_node = Node ( new_data ) NEW_LINE new_node . data = new_data NEW_LINE new_node . next = head_ref NEW_LINE head_ref = new_node NEW_LINE return head_ref NEW_LINE DEDENT def prList ( node ) : NEW_LINE INDENT while ( node != None ) : NEW_LINE INDENT print ( node . data , end = " ▁ " ) NEW_LINE node = node . next NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = None NEW_LINE head = push ( head , 2 ) NEW_LINE head = push ( head , 1 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 5 ) NEW_LINE head = push ( head , 3 ) NEW_LINE sortList ( head ) NEW_LINE prList ( head ) NEW_LINE DEDENT