题目
将链表
1->2->3->4->5->6->7…->n-1->n
变为
1->n->2->n-1->…
请使用原地变化。
解法
- 首先,使用快慢指针,得到链表的中心节点
- 然后,从slow指针指向的位置开始反转后半段链表
- 然后对两个链表执行交错指向
代码
#include <iostream>
using namespace std;
struct Node {
int val;
Node *next;
Node(int _val) {
val = _val;
next = nullptr;
}
};
Node *func(Node *node) {
Node *slow = node;
Node *fast = node;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
Node *p1 = node;
Node *p2 = nullptr;
Node *pre = nullptr;
Node *cur = slow;
while (cur != nullptr) {
Node *tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
p2 = pre;
while (p2->next != nullptr) {
auto tmp = p1->next;
p1->next = p2;
auto tmp_p2_next = p2->next;
p2->next = tmp;
p1 = tmp;
p2 = tmp_p2_next;
}
return node;
}
int main() {
// char str[3];
// std::cin>>str;
std::cout << "hello world" << std::endl;
int N = 10;
Node *root = new Node(1);
Node *p = root;
for (auto i = 2; i <= 10; i++) {
Node *node = new Node(i);
p->next = node;
p = p->next;
}
auto res = func(root);
p = res;
while (p != nullptr) {
std::cout << p->val << "->";
p = p->next;
}
return 0;
}