原题如下:
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) {
int len = 0;
ListNode *p = head;
while(p != NULL){
len++;
p = p->next;
}
if(len < k)
return head;
int m = len / k; //共m部分
ListNode *tHead = new ListNode(0);
ListNode *cur,*postCur,*q = NULL;
cur = head;
postCur = cur->next;
p = tHead;
for(int i = 0; i < m; i++){
for(int j = 0; j < k; j++){
postCur = cur->next;
cur->next = p->next;
p->next = cur;
if(j == 0)
q = cur;
cur = postCur;
}
p = q;
}
p->next = cur;
head = tHead->next;
delete tHead;
return head;
}
};
上述算法的时间复杂度为O(n),需要一个节点的的额外空间。