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

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of

时间:2017-07-01 20:08:51      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:pos   modified   highlight   blog   lin   linked   i++   reverse   tno   

class Solution {  
public:  
    ListNode *reverseKGroup(ListNode *head, int k) {  
        if (!head || !(head->next) || k < 2)  
            return head;  
          
        // count k nodes  
        ListNode *nextgp = head;  
        for (int i = 0; i < k; i++)  
            if (nextgp)  
                nextgp = nextgp->next;  
            else  
                return head;  
  
        // reverse  
        ListNode *prev = NULL, *cur = head, *next = NULL;  
        while (cur != nextgp) {  
            next = cur->next;  
            if (prev)  
                cur->next = prev;  
            else  
                cur->next = reverseKGroup(nextgp, k);  
            prev = cur;  
            cur = next;  
        }  
        return prev;  
    }  
};

  

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of

标签:pos   modified   highlight   blog   lin   linked   i++   reverse   tno   

原文地址:http://www.cnblogs.com/Czc963239044/p/7103235.html

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