Reverse Nodes in k-Group
描述:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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
代码:
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (head == NULL || head->next == NULL || k < 2) {
return head;
}
ListNode dummy(-1);
dummy.next = head;
for (ListNode *prev = &dummy, *end = head; end; end = prev->next) {
for (int i = 1; i < k && end; i++) {
end = end->next;
}
if (end == NULL) { //不足k个
break;
}
prev = reverse(prev, prev->next, end);
}
return dummy.next;
}
//prev是first前一个元素,[begin,end]闭区间,保证三者都不为NULL
ListNode *reverse(ListNode *prev, ListNode *begin, ListNode *end) {
ListNode *end_next = end->next;
for (ListNode *p = begin, *cur = p->next, *next = cur->next; cur != end_next; p = cur, cur = next, next = next ? next->next : NULL) {
cur->next = p;
}
begin->next = end_next;
prev->next = end;
return begin;
}
};