您的位置:首页 > Web前端 > Node.js

25. Reverse Nodes in k-Group

2017-01-31 00:31 309 查看
1刷

上面一提的加强版,思路很简单,每k个就调用一个函数换一次

难点!小细节,这种错!要十分注意每一次换了位置之后的前后的指针标记会变化!!!

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void changethelist(ListNode* a, ListNode* b, ListNode* first, ListNode* end){
ListNode *t1, *t2, *t;
t1 = a;
t2 = a -> next;
while(t2 != b){
t = t2 -> next;
t2 -> next = t1;
t1 = t2;
t2 = t;
}
t2 -> next = t1;

if(first != NULL)
first -> next = b;
a -> next = end;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(head == NULL || k == 1) return head;
ListNode *h, *a, *last, *n;
h = head;
int num = 0;
while(head != NULL){
num++;
if(num == k) h = head;
if(num % k == 1) a = head; //if(num % k == 1 && num != 1) return head;
if(num == k){
n = head -> next;
changethelist(a, head, NULL, head -> next);
last = a;
head = n;
}
else if(num % k == 0){
n = head -> next;
changethelist(a, head, last, head -> next);
last = a;
head = n;
}
else{
head = head -> next;
continue;
}
}
return h;
}
};


2刷

还是链表的各种操作,要3刷,2刷再次学了方法

/**
* 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==NULL||k==1) return head;
int num=0;
ListNode *preheader = new ListNode(-1);
preheader->next = head;
ListNode *cur = preheader, *nex, *pre = preheader;
while(cur = cur->next)
num++;
while(num>=k) {
cur = pre->next;
nex = cur->next;
for(int i=1;i<k;++i) {
cur->next=nex->next;
nex->next=pre->next;
pre->next=nex;
nex=cur->next;
}
pre = cur;
num-=k;
}
return preheader->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: