Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list's nodes, only nodes itself may be changed.
题意:
给定一个链表,每k个节点一组,做一次反转。
Solution1:we can still simplify this question into how to reverse a linked list, the only difference is we need to set "dummy" and "null" like the left and right boundary by ourselves.
(1) set a pointer pre as a " dummy " ahead
(2) set a pointer last as a " null " boundary
(3) iteratively move cur into the front(pre.next)
(4) cur = next
(5)iteratively move cur into the front(pre.next) until cur meet the "null" boundary
code:
/*
Time: O(n)
Space: O(1)
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null) return null;
ListNode dummy = new ListNode(-1);
ListNode pre = dummy;
dummy.next = head;
// to reverse each k-Group, considering pre as a "dummy" ahead
while (pre != null) {
pre = reverse(pre, k);
}
return dummy.next;
} public ListNode reverse(ListNode pre, int k) {
// to reverse each k-Group, considering last as a "null" boundary
ListNode last = pre;
for (int i = 0; i < k + 1; i++) {
last = last.next;
if (i != k && last == null) return null;
} // reverse
ListNode tail = pre.next;
ListNode cur = pre.next.next;
// remove cur to front, then update cur
while (cur != last) {
ListNode next = cur.next;
cur.next = pre.next;
pre.next = cur;
tail.next = next;
cur = next;
}
return tail;
}
}