143 重排链表
Posted innovationv2
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了143 重排链表相关的知识,希望对你有一定的参考价值。
方法一 活用set
void reorderList(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return;
set<ListNode *> save;
int len = 1;
ListNode *t = head;
for (; t->next != nullptr; t = t->next)
++len;
int mid = len % 2 == 0 ? len / 2 : (len + 1) / 2;
t = head;
for (; mid > 0; --mid)
t = t->next;
while (t != nullptr) {
save.insert(t);
t = t->next;
}
t = head;
auto end = --save.end();
for (auto size = save.size(); size > 0; --size) {
(*end)->next = t->next;
t->next = *end;
t = t->next->next;
--end;
}
t->next = nullptr;
}
方法二 快慢指针找中点然后反转后半部分链表,然后插入到前半个链表当中去
ListNode *reverse(ListNode *head) {
ListNode *front = head, *rear = nullptr, *temp = nullptr;
while (front != nullptr) {
temp = front->next;
front->next = rear;
rear = front;
front = temp;
}
return rear;
}
void reorderList(ListNode *head) {
if(head== nullptr||head->next== nullptr)
return;
auto *prehead = new ListNode(0);
prehead->next = head;
ListNode *fast = prehead, *slow = prehead;
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
if (fast->next == nullptr)
break;
fast = fast->next;
}
slow = reverse(slow->next);
fast = head;
while (slow != nullptr) {
ListNode *temp = slow->next;
slow->next = fast->next;
fast->next = slow;
slow = temp;
fast = fast->next->next;
}
fast->next = nullptr;
}
以上是关于143 重排链表的主要内容,如果未能解决你的问题,请参考以下文章