Given a linked list, write a function to reverse every alternate k nodes (where k is an input to the function) in an efficient way. Give the complexity of your algorithm.
Example: Inputs: 1->2->3->4->5->6->7->8->9->NULL and k = 3 Output: 3->2->1->4->5->6->9->8->7->NULL.
Method 1 (Process 2k nodes and recursively call for rest of the list)
This method is basically an extension of the method discussed in this post.
kAltReverse(struct node *head, int k) 1) Reverse first k nodes. 2) In the modified list head points to the kth node. So change next of head to (k+1)th node 3) Move the current pointer to skip next k nodes. 4) Call the kAltReverse() recursively for rest of the n - 2k nodes. 5) Return new head of the list.
Given linked list
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Modified Linked list
3 2 1 4 5 6 9 8 7 10 11 12 15 14 13 16 17 18 20 19
Time Complexity: O(n)
Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem.
- Alternate Odd and Even Nodes in a Singly Linked List
- Given a linked list, reverse alternate nodes and append at the end
- Sum of the nodes of a Singly Linked List
- C Program to reverse each node value in Singly Linked List
- Product of the nodes of a Singly Linked List
- Sum of the alternate nodes of linked list
- Delete all Non-Prime Nodes from a Singly Linked List
- Sum and Product of the nodes of a Singly Linked List which are divisible by K
- Sum and Product of all Prime Nodes of a Singly Linked List
- Delete all Prime Nodes from a Singly Linked List
- Count of Prime Nodes of a Singly Linked List
- Find the common nodes in two singly linked list
- Product of the alternate nodes of linked list
- Delete alternate nodes of a Linked List
- Sum and Product of the nodes of a Circular Singly Linked List which are divisible by K