现在的位置: 首页 > 综合 > 正文

leetcode Reverse Nodes in k-Group

2019年08月14日 ⁄ 综合 ⁄ 共 460字 ⁄ 字号 评论关闭

递归一下

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

抱歉!评论已关闭.