[LeetCode 25] K 个一组翻转链表


给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group


class Solution {
public:
    ListNode* reverse(ListNode* head) {
        auto p=head, q=p->next;
        while(q) {
            auto r=q->next;
            q->next=p;
            p=q;
            q=r;
        }
        head->next=nullptr;
        return p;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        auto daemon=new ListNode(0, head);
        auto p=daemon;
        while(true) {
            auto r=p->next;
            auto q=p;
            int c=0;
            while(cnext) {
                c++;
                q=q->next;
            }
            if(cnext=nullptr;
            auto t=q->next;
            q->next=nullptr;
            reverse(r);
            p->next=q;
            r->next=t;
            p=r;
        }
        auto x=daemon->next;
        delete daemon;
        return x;
    }
};

相关