Algo-Sim › Linked Lists
Reverse Nodes in k-Group
Hard · Linked Lists · step through it in Java, Python and C++ on your own input
Reverse every block of k nodes in place, leaving a shorter last block as it is.
Problem
Reverse the nodes of the list k at a time and return the new head. If the number of nodes left at the end is less than k, leave those nodes in their original order. Only change links, not values.
Constraints
- 1 ≤ k ≤ number of nodes ≤ 5000
- 0 ≤ Node.val ≤ 1000
- Follow-up: O(1) extra memory
Edge cases to test
- k = 1: unchanged
- Length not a multiple of k: the tail stays
- k equals the length
Follow-up questions
- Why count k nodes before reversing?
- A short last group must stay as it is, so check it exists first: O(n) time, O(1) space.
- What if the short last group should be reversed too?
- Drop the length check and reverse whatever is left.
Solution
Java
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head), groupPrev = dummy;
while (true) {
ListNode kth = groupPrev;
for (int i = 0; i < k && kth != null; i++) kth = kth.next;
if (kth == null) break;
ListNode groupNext = kth.next;
ListNode prev = groupNext, curr = groupPrev.next;
while (curr != groupNext) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
ListNode first = groupPrev.next;
groupPrev.next = kth;
groupPrev = first;
}
return dummy.next;
}Python
def reverse_k_group(head, k):
dummy = ListNode(0, head)
group_prev = dummy
while True:
kth = group_prev
for _ in range(k):
if kth:
kth = kth.next
if not kth:
break
group_next = kth.next
prev, curr = group_next, group_prev.next
while curr is not group_next:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
first = group_prev.next
group_prev.next = kth
group_prev = first
return dummy.nextC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *dummy = new ListNode(0, head), *groupPrev = dummy;
while (true) {
ListNode *kth = groupPrev;
for (int i = 0; i < k && kth != nullptr; i++)
kth = kth->next;
if (kth == nullptr)
break;
ListNode *groupNext = kth->next;
ListNode *prev = groupNext, *curr = groupPrev->next;
while (curr != groupNext) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
ListNode *first = groupPrev->next;
groupPrev->next = kth;
groupPrev = first;
}
return dummy->next;
}
};
More Linked Lists problems
- Reverse Linked List (Easy)
- Reverse Linked List (Recursive) (Easy)
- Merge Two Sorted Lists (Easy)
- Middle of the Linked List (Easy)
- Palindrome Linked List (Easy)
- Linked List Cycle (Easy)
- Linked List Cycle II (Medium)
- Intersection of Two Linked Lists (Easy)
- Find the Duplicate Number (Medium)
- Remove Nth Node From End of List (Medium)
- Reorder List (Medium)
- Sort List (Medium)
- Add Two Numbers (Medium)
- Copy List with Random Pointer (Medium)