問題描述
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
問題分析
- ans是最終結果的表頭指針;
- ans_p是負責組間連接工作的結點指針;
- p是負責檢查是否還有k個結點需要逆轉的結點指針;
- p1用來記錄逆轉前的組的表頭指針;
- q爲逆轉過程中的表頭指針。
代碼
<pre name="code" class="cpp">//運行時間:38ms
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (!head) return NULL;
if (k<=1) return head;
ListNode *ans = NULL;
ListNode *ans_p = head;
ListNode *p = head;//前進!
ListNode *p1;
ListNode *q = head;
ListNode *x;
ListNode *y;
int count ;
while (1){
count = 0;
p1 = p;
while (p&&count < k){
count++;
p = p->next;
}
if (count < k) {
if (!ans) ans = p1;
else{ ans_p->next = p1; }
break;
}
else{
x = y = q->next;
count = 1;
while (count < k){
x = x->next;
y->next = q;
q = y;
y = x;
count++;
}
if (!ans) { ans = q; ans_p = p1; }
else { ans_p->next = q; ans_p = p1; }
q = p;
}
if (!p) break;
}
return ans;
}
};