#include<vector>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int _x) : val(_x), next(nullptr) {}
ListNode(int _x, ListNode* _next) : val(_x), next(_next) {}
};
ListNode* buildList(vector<int>& num1)
{
ListNode* head = new ListNode(num1[0]);
ListNode* tmp = head;
for (int i = 1; i < num1.size(); i++)
{
ListNode* node = new ListNode(num1[i]);
tmp->next = node;
tmp = tmp->next;
}
return head;
}
pair<ListNode*, ListNode*> reverseList(ListNode* head, ListNode* tail)
{
ListNode* tmp = tail->next;
ListNode* cur = head;
while (tmp != tail)
{
ListNode* node = cur->next;
cur->next = tmp;
tmp = cur;
cur = node;
}
return { tail, head };
}
ListNode* revsK(ListNode* head, int K)
{
ListNode* headFront = new ListNode(-1);
headFront->next = head;
ListNode* pre = headFront;
while (head)
{
ListNode* tail = pre;
for (int i = 0; i < K; i++)
{
tail = tail->next;
if (!tail)
{
return headFront->next;
}
}
ListNode* next = tail->next;
pair<ListNode*, ListNode*> res = reverseList(head, tail);
head = res.first;
tail= res.second;
pre->next = head;
tail->next = next;
pre = tail;
head = tail->next;
}
return headFront->next;
}
int main() {
vector<int> num1 = { 1,2,3,4,5,6,7,8,9 };
ListNode* node = buildList(num1);
ListNode* res = revsK(node, 3);
ListNode* tmp = res;
while (res)
{
cout << res->val << "->";
res = res->next;
}
}
面试题模拟,反转3次链表
最新推荐文章于 2024-05-09 18:10:33 发布