Reverse a Linked List in groups of given size.
Given a linked list, write a function to reverse every k nodes .
Example:
If a linked list is given as 1->2->3->4->5->6->7->8->NULL and k = 3 then,
Output will be 3->2->1->6->5->4->8->7->NULL.
Algorithm:
- It a variant of {@link ReorderList}, in that k was 2
- Set some variable before starting iteration process
newHead = null, current = node, next, prev, prevPrev = node and bachStartNode
- Iterate till
node ! = null
- Set
prev = null, counter = 0 and bachStartNode = node
- Iterate till
node != null and counter < k
next = node.next
node.next = prev
prev = node
node = next
- if
prevPrev != null
prevPrev.next = prev
PrevPrev = bachStartNode
- Set
Latest Source Code:
Github: KReverseList.java
Output:
1 2 3 4 5 6 7 8 2 1 4 3 6 5 8 7 1 2 3 4 5 6 7 8 3 2 1 6 5 4 8 7 1 2 3 4 5 6 7 8 4 3 2 1 8 7 6 5