25. Reverse Nodes in k-Group

Posted The Tech Road

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了25. Reverse Nodes in k-Group相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group

25. Reverse Nodes in k-Group(js)

LeetCode - 25. Reverse Nodes in k-Group