递归一下
/** * 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; } };
leetcode Reverse Nodes in k-Group,布布扣,bubuko.com
leetcode Reverse Nodes in k-Group
原文地址:http://blog.csdn.net/qxietingwen/article/details/27963323