首页 > 代码库 > leetcode Reverse Nodes in k-Group

leetcode Reverse Nodes in k-Group

递归一下


/**
 * 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;
        
    }
};