leetcode-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,

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

void List::reverse()
{
p->next = NULL;//将头接点之后的第1个节点的next指针置为空
//根据m是否为空来判断 以此逆序每一个节点
while(m){
q->next = p;
p = q;
q = m;
m = m->next;
}
//将最后一个节点逆序
q->next = p;
//将头从新指向新的的第1个节点(之前的最后一个节点)
}

reverse函数输入pre->顺序序列->end

CPP代码如下。注视部分有问题待解决。

class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* dummy = new ListNode(0);
int count = 0;
ListNode* pre = dummy;
while(cur != NULL)
{
count ++;
cur=cur->next;
//ListNode* next = cur->next;
if(count == k)
{
pre = reverse(pre, cur);
count = 0;
}
//cur = next;
}
return dummy->next;
}
ListNode* reverse(ListNode* pre, ListNode* end)  {
if(pre==NULL || pre->next==NULL)
return pre;
ListNode* cur = pre->next->next;
while(cur!=end)
{
ListNode* next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = next;
}
/*ListNode * x=pre->next;
x->next=NULL;
ListNode * p = pre->next;//头结点之后的第1个节点
ListNode * q = pre->next->next;//头结点之后的第2节点
ListNode * m = pre->next->next->next;//头结点之后的第3个节点
p->next = NULL;
while(m!=end){
q->next = p;
p = q;
q = m;
m = m->next;
}
q->next = p;
x->next=m;
pre->next = q;
return x;*/
}
};

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *s,*p=(ListNode*)malloc(sizeof(ListNode));
int len=k;
while(k-- && s!=NULL)s=s->next;
while(s!=NULL){
reverse(p,s);
k=len;
while(k-- && s!=NULL)s=s->next;
}
}
private:
void reverse(ListNode* &p,ListNode* &s){
ListNode *tmp,*tail=p->next,*flag=s->next,*l=p->next;
p->next=NULL;
while(l!=flag){
tmp=p->next;
p->next=l;
l=l->next;
p->next->next=tmp;
}
tail->next=l;
p=tail;
s=tail;
}
};

02-26 1.2万

05-11 1059

06-08 3971

06-02 819

09-05 267

03-05 2888

01-08 483

12-17 1684

10-30 1100

11-17 276