#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);
}
Leecode k个一组反转链表
最新推荐文章于 2024-11-09 20:38:27 发布