递归一下
/**
* 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 ||head->next==NULL||k<=1)
return head;
int n=k;
int len=0;
ListNode *p=head;
while(p)
{
len++;
p=p->next;
}
if(len<k)
return head;
ListNode *q=head;
p=NULL;
while(q&&n>0)
{
ListNode *ne=q->next;
q->next=p;
p=q;
q=ne;
n--;
}
if(len-k>=k)
head->next=reverseKGroup(q,k);
else
head->next=q;
return p;
}
};
版权声明:本文为Qxietingwen原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。