欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 25. K 个一组翻转链表

程序员文章站 2022-07-08 14:46:39
...

LeetCode 25. K 个一组翻转链表

算法步骤:
1.先让k内部的指针方向改变
2.令c = p->next,然后p->next = a,c->next = b,更新p = c

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        auto dummy = new ListNode(-1);
        dummy->next = head;
		// 为什么这里还有个for循环?链表里存在n个k
        for(auto p = dummy;;){
            auto q = p;
            for(int i = 0; i < k && q; i ++) q = q->next;
            if(!q) break;

            auto a = p->next, b = a->next;
            for(int j = 0; j < k - 1; j ++){
                auto c = b->next;
                b->next = a;
                a = b, b = c; 
            }
            auto c = p->next;
            p->next = a;
            c->next = b;
            p = c;
        }

        return dummy->next;
    }
};
相关标签: LeetCode