首页 > 其他 > 详细

25. Reverse Nodes in k-Group

时间:2018-05-18 14:48:11      阅读:177      评论:0      收藏:0      [点我收藏+]

https://leetcode.com/problems/reverse-nodes-in-k-group/description/

/**
 * 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) {
        ListNode h(0);
        ListNode *pre = &h;
        while (true) {
            ListNode* tail = head;
            int i = 1; 
            for (; i < k && tail; i++)
                tail = tail->next;
            if (tail) {
                ListNode* tailNext = tail->next;
                reverseList(head, tailNext);
                pre->next = tail;
                head->next = tailNext;
                
                pre = head;
                head = tailNext;
            }
            else {
                pre->next = head;
                break;
            }
        }
        return h.next;
    }
    void reverseList(ListNode* head, ListNode* tail) {
        ListNode* pre = NULL;
        while (head != tail) {
            ListNode* p = head->next;
            head->next = pre;
            pre = head;
            head = p;
        }
    }
};

 

25. Reverse Nodes in k-Group

原文:https://www.cnblogs.com/JTechRoad/p/9056147.html

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