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(len0)
        {
            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)