Find the sum of last n nodes of the given Linked List | 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 point to the new node ; utility function to find the sum of last ' n ' nodes ; if n == 0 ; traverses the list from left to right ; push the node ' s ▁ data ▁ onto ▁ the ▁ stack ▁ ' st ; move to next node ; pop ' n ' nodes from ' st ' and add them ; required sum ; Driver Code ; create linked list 10.6 .8 .4 .12
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . next = None NEW_LINE DEDENT DEDENT head = None NEW_LINE n = 0 NEW_LINE sum = 0 NEW_LINE def push ( head_ref , new_data ) : NEW_LINE INDENT global head NEW_LINE new_node = Node ( 0 ) 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 DEDENT def sumOfLastN_NodesUtil ( head , n ) : NEW_LINE INDENT global sum NEW_LINE if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT st = [ ] NEW_LINE sum = 0 NEW_LINE while ( head != None ) : NEW_LINE INDENT st . append ( head . data ) NEW_LINE head = head . next NEW_LINE DEDENT while ( n ) : NEW_LINE INDENT n -= 1 NEW_LINE sum += st [ 0 ] NEW_LINE st . pop ( 0 ) NEW_LINE DEDENT return sum NEW_LINE DEDENT head = None NEW_LINE push ( head , 12 ) NEW_LINE push ( head , 4 ) NEW_LINE push ( head , 8 ) NEW_LINE push ( head , 6 ) NEW_LINE push ( head , 10 ) NEW_LINE n = 2 NEW_LINE print ( " Sum ▁ of ▁ last " , n , " nodes ▁ = " , sumOfLastN_NodesUtil ( head , n ) ) NEW_LINE