Rotate linked list C implementation

Rotate Linked List

Given a singly linked list, rotate linked list by K nodes clockwise. For example:

Original list : 1->2->3->4->5->NULL  K = 2
Rotated list : 3->4->5->1->2->NULL;

List : 1->3->4->5->6->7->9->10->NULL K = 4
Rotated list: 6->7->9->10->1->3->4->5->NULL

Only aim of this problem is to see if you can understand traversal of list and pointer changes. Algorithm to rotate a list is very simple as below:

1. Traverse K nodes. Store Kth node as KthNode
2. Continue traverse till end of last node of list.
3. Now point next of last node to head of list.
4. Change head to point to next of KthNode
5. Make next node of KthNode as NULL

Implementation of above algorithm

Output

2->4->6->8->10->12->NULL K = 2
6->8->10->12->2->4->NULL

Complexity of algorithm to rotate a list is O(n) as we have to traverse the entire list once. No extra space required.

Please share your thoughts and views. We would love to hear what you have to say. Sharing is caring.