In this post, we will discuss a method to Rotate the Linked List in an Anti-clockwise direction. This is one of the easy questions asked in coding interviews. There are a lot of approaches that one can try using for this problem, below algorithm according to me is one of the simpler approaches if not the best. To rotate a linked list we simply need to link the tail node to the head node and move the head pointer to the next node, we repeat this step according to shift value. Let's have a look at below algorithm. We use 2 pointers for this algorithm, current node and tail node, the current node initially points to the head node and will become the new head node after our operations and tail node marks the end of the linked list.
Algorithm:
- consider 2 nodes current node and tail node.
- Initialize current node to point to the head of the Linked List
- Initialize tail node to point to the head of the Linked List
- Move the tail pointer and make tail point the last element
- Repeat the below steps and decrease the shift values while it becomes 0
- update tail nodes link to a current node
- update current node to point to next node
- update tail node to point to next node
- update tail node's link to Null
- Make current node as the new head node
- Return Head node
There can be a lot of different approaches used to solve the above problem, comment down and let me know your approach. Also, Comment down how would you rotate the linked list in clockwise direction, I'll make a post for that problem soon. Now let's have a look at the code
Comments
Post a Comment