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 ; Calculate the length of the linked list ; Count of first ( len - n ) Nodes ; Just traverse the 1 st ' c ' Nodes ; Move to next Node ; Now traverse the last ' n ' Nodes and add them ; Accumulate Node 's data to sum ; Move to next Node ; 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 sumOfLastN_NodesUtil ( head , n ) : NEW_LINE INDENT if ( n <= 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT sum = 0 NEW_LINE len = 0 NEW_LINE temp = head NEW_LINE while ( temp != None ) : NEW_LINE INDENT len += 1 NEW_LINE temp = temp . next NEW_LINE DEDENT c = len - n NEW_LINE temp = head NEW_LINE while ( temp != None and c > 0 ) : NEW_LINE INDENT temp = temp . next NEW_LINE c -= 1 NEW_LINE DEDENT while ( temp != None ) : NEW_LINE INDENT sum += temp . data NEW_LINE temp = temp . next NEW_LINE DEDENT 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 ( head , n ) ) NEW_LINE DEDENT