Learn basic concept of c , c++ and python programming in regularcodes.com

Spread the post

Sum of last n terms in given linked list

Suppose following data are inserting in linked list.

input : 1 2 3 4 5 6 7 8 .

n number of last node. n=4

Sum of last [4] node is: [26].

Another example n=3.

Sum of last [3] node is: [21].

Sum of last n node

View insertion at beginning.

Try it yourself

Algorithm:

In recursive approach are use sum_node function three parameter. one is temp pointer which are point to root or head of given linked list. and second parameter is counter pointer variable to define how many number of last node are to sum . and third one is result pointer variable that are initial zero.

Passing this three parameter initially next pass temp pointer are pointed to next memory block and other two parameter are same. Continue this process until temp pointer are not NULL.

After return sum_node function. And counter pointer value is greater than 0 that means add this node. add node data in result pointer value.

Code execution:

Stack Areamainfind (int) =0last_node (int) =3result (int) =21root(pointer)sum_nodecounter(pointer)result(pointer)temp(pointer) Heap Areastruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 3next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 5next (pointer) struct Nodedata (int)= 6next (pointer) struct Nodedata (int)= 7next (pointer) struct Nodedata (int)= 8next (pointer)= NULL

Note that not given all step of execution process here.View How to insert linked list element and so on.

Try it yourself

C program to find and detect loop of given linked list.

OutPut:

Spread the post