25. 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
解析:循环k次,依次将所到节点插入到prev节点的后面,
-1 -> 1 -> 2 -> 3 -> 4 -> 5
| | | |
pre cur nex tmp
-1 -> 2 -> 1 -> 3 -> 4 -> 5
| | | |
pre cur nex tmp
-1 -> 3 -> 2 -> 1 -> 4 -> 5
| | | |
pre cur nex tmp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(!head || !head->next || k == 1) return head;
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *prev = dummy, *cur = head, *after;
//求数组长度
int length = 0;
while(cur){
length++;
cur = cur->next;
}
while(length >= k){
cur = prev->next;
after = cur->next;
for(int i = 1; i < k; i++){
//将after节点插入到prev后面
cur->next = after->next;
after->next = prev->next;
prev->next = after;
//特别注意这一行(因为还要循环啊)
after = cur->next;
}
prev = cur;
length -= k;
}
return dummy->next;
}
};