Leecode k个一组反转链表

#include <iostream>
using namespace std;
#include <vector>
#include <algorithm>
class ListNode {
public:
    int val;
    ListNode* next = nullptr;
    ListNode(int x) {
        this->val = x;
    }
};

class solution {
public:
    void printList(ListNode* head) {
        while (head) {
            cout << head->val << " ";
            head = head->next;
        }
        cout << endl;
    }

    vector<ListNode*> reverseK(vector<ListNode*> t) {
        ListNode* head = t[0];
        ListNode* tail = t[1];
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* pre = dummy;
        while (pre != tail) {
            ListNode* node = head->next;
            head->next = pre;
            pre = head;
            head = node;
        }
        t[0] = tail;
        t[1] = dummy->next; 
        return t;
    }

    ListNode* ListNodeReverse(ListNode* head, int k) {
        ListNode* dummynode = new ListNode(-1);
        dummynode->next = head;
        ListNode* cur = dummynode;
        ListNode* pre = dummynode;
        int num = 0;
        while (cur) {
            
            if (num == k) {
                ListNode* nxt = cur->next;
                vector<ListNode*> t(2);
                t[0] = pre->next;
                t[1] = cur;
                t = reverseK(t);
                ListNode* reverseHead = t[0];
                ListNode* reverseTail = t[1];
                reverseTail->next = nxt;
                pre->next = reverseHead;
                cur = reverseTail;
              
                num = 0;
            }
                
                cur = cur->next;
                num++;
        }
        return dummynode->next;
    }
};

int main() {
    ListNode* head = new ListNode(1);
    ListNode* cur = head;
    for (int i = 0; i < 4; ++i) {
        ListNode* node = new ListNode(i + 2);
        cur->next = node;
        cur = cur->next;
    }
    solution s;
    s.printList(head);
    ListNode* res = s.ListNodeReverse(head, 3);
    s.printList(res);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值