首页 > 其他 > 详细

LeetCode 25 Reverse Nodes in k-Group

时间:2019-07-09 20:00:15      阅读:128      评论:0      收藏:0      [点我收藏+]

题目

/**
 * 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) {
        
        
        int num=0;
        ListNode* temp = head;
        while(temp!=NULL)
        {
            num++;
            temp = temp->next;
        }
        
        if(k>num||k==1)
            return head;
        
        ListNode* start;
        ListNode* end;
        ListNode* pre;
        ListNode* res;
        
        pre = res = new ListNode(0);
        temp = head;
        int pos=0;
        while(temp!=NULL)
        {

            if((pos==0 || pos%k==0))
            {
                if(num-pos<k)
                    break;
                
                if(pos!=0){
                    pre = end;
                }
                
                start = temp;
                end = temp;
                
                temp=temp->next;
                pos++;
            }
            else
            {
                ListNode* term = temp;
                temp = temp->next;
                end->next = term->next;
                term->next = start;
                pre->next = term;
                start=term;
                //pre->next = start;
                
                
                pos++;
            }
        }
        return res->next; 
    }
};

LeetCode 25 Reverse Nodes in k-Group

原文:https://www.cnblogs.com/dacc123/p/11159685.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!