Find the sum of last n nodes of the given Linked List | A Linked list Node ; Function to insert a Node at the beginning of the linked list ; Allocate Node ; Put in the data ; Link the old list to the new Node ; Move the head to poto the new Node ; utility function to find the sum of last ' n ' Nodes ; if n == 0 ; reverse the linked list ; traverse the 1 st ' n ' Nodes of the reversed linked list and add them ; accumulate Node ' s ▁ data ▁ to ▁ ' sum ; move to next Node ; reverse back the linked list ; required sum ; Driver code ; create linked list 10.6 .8 .4 .12
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . next = None NEW_LINE DEDENT DEDENT head = None NEW_LINE 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 head = head_ref NEW_LINE return head NEW_LINE DEDENT def reverseList ( ) : NEW_LINE INDENT global head ; NEW_LINE current , prev , next = None , None , None ; NEW_LINE current = head ; NEW_LINE prev = None ; NEW_LINE while ( current != None ) : NEW_LINE INDENT next = current . next ; NEW_LINE current . next = prev ; NEW_LINE prev = current ; NEW_LINE current = next ; NEW_LINE DEDENT head = prev ; NEW_LINE DEDENT def sumOfLastN_NodesUtil ( n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT reverseList ( ) ; NEW_LINE sum = 0 ; NEW_LINE current = head ; NEW_LINE while ( current != None and n > 0 ) : NEW_LINE INDENT sum += current . data ; NEW_LINE current = current . next ; NEW_LINE n -= 1 ; NEW_LINE DEDENT reverseList ( ) ; NEW_LINE return sum ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT head = push ( head , 12 ) NEW_LINE head = push ( head , 4 ) NEW_LINE head = push ( head , 8 ) NEW_LINE head = push ( head , 6 ) NEW_LINE head = push ( head , 10 ) NEW_LINE n = 2 ; NEW_LINE print ( " Sum ▁ of ▁ last ▁ " , n , " ▁ Nodes ▁ = ▁ " , sumOfLastN_NodesUtil ( n ) ) ; NEW_LINE DEDENT