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

Spread the post

Remove every k-th node of the linked list

Suppose given linked list contain following nodes [1,2,3,4,5,6,7,8,9,10]. Our goal is to delete every k-th node of linked list.

K is a position of to delete node. given of few examples of this problem.

Accepted Output


root_ptr10987654321

View insertion process.

Try it Yourself

Given [k=3]

root_ptr10987654321

View 3rd position of given linked list.

After delete 3rd position nodes.

root_ptr10875421

Algorithm:


Time complexity of this program O(n).

Note that if k==1 then delete all linked list nodes.

C program to Remove every k-th node of the given linked list.


Output


Code execution

Origanl linked list.

Stack Areamainroot(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) struct Nodedata (int)= 9next (pointer) struct Nodedata (int)= 10next (pointer)= NULL

After remove [3 rd] position.

Stack Areamainroot(pointer)remove_kthcount (int) =1free_node(pointer) NULLkth (int) =3root(pointer)temp(pointer) Heap Areastruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 6next (pointer) struct Nodedata (int)= 8next (pointer) struct Nodedata (int)= 10next (pointer)= NULL

After remove every 4th nodes.

Stack Areamainroot(pointer)remove_kthcount (int) =2free_node(pointer) NULLkth (int) =4root(pointer)temp(pointer) Heap Areastruct Nodedata (int)= 1next (pointer) struct Nodedata (int)= 2next (pointer) struct Nodedata (int)= 4next (pointer) struct Nodedata (int)= 8next (pointer) struct Nodedata (int)= 10next (pointer)= NULL

Note given all execution process.

Try it Yourself

Spread the post

Recommended Posts: