Let’s directly look at the algorithm and code to understand it better
Algorithm:
- In the above code, we use 3 pointers current, previous and next.
- Initially, the current node points to the head node, the previous and next nodes are Null
- Then we use a while loop to traverse through the linked list and also decrease k
- In each iteration, we do the following
- assign next pointer to current node's link field
- update current nodes link field to point to the previous node
- update the previous node to point to the current node
- when k is 0 then previous node points to the starting of the linked list so we assign it to the head node
- We also need to join the link between the current node and the next node
- Return head node
Suggestion: To understand the algorithm and its working better try doing a dry run on the paper by considering a simple linked list.
C++ Program
Sample input and output to check the program
You might also be interested in
Comments
Post a Comment