码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode Reverse Nodes in k-Group

时间:2014-06-01 17:35:40      阅读:406      评论:0      收藏:0      [点我收藏+]

标签:des   c   class   blog   code   a   

递归一下


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

标签:des   c   class   blog   code   a   

原文地址:http://blog.csdn.net/qxietingwen/article/details/27963323

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!