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

Reverse Nodes in k-Group

2015-07-11 20:30 555 查看
class Solution {

public:

ListNode* reverseKGroup(ListNode* head, int k) {

ListNode* p=head;

int len=0;

if(head==NULL||head->next==NULL) return head;

while(p)

{

len++;

p=p->next;

}

int m=1,n=k;

while(n<=len)

{

head=reverseBetween(head,m,n);

m=m+k;

n=n+k;

}

return head;

}

ListNode* reverseList(ListNode* head) {

if(head==NULL) return head;

if(head->next==NULL) {return head;}

ListNode* p=head;

ListNode* p1;

ListNode* p2;

p1=p->next;

p2=p->next->next;

p->next=NULL;

while(p2)

{

p1->next=p;

p=p1;

p1=p2;

p2=p2->next;

}

p1->next=p;

return p1;

}

ListNode* reverseBetween(ListNode* head, int m, int n) {

int count=1;

ListNode* p=head,*pre,*plast,*head1,*head2;

if(head==NULL||head->next==NULL) return head;

// ListNode* pre;

while(count<m-1)

{

p=p->next;

count++;

}

pre=p;

head1=p->next;

if(m==1)

head1=head;

while(count<n)

{

p=p->next;

count++;

}

plast=p->next;

p->next=NULL;

head2=reverseList(head1);

if(m==1&&n!=1){ head1->next=plast;return head2;}

else{

pre->next=head2;

head1->next=plast;}

return head;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: