Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
链表操作的思路往往比较容易想,但是实现起来就非常复杂。
这里思路就是
1.将链表分为前后两部分
2.将后部分链表反转,这里反转我使用了一种新的方法(制造一个新的链表,将旧链表的结点依次添加到新链表的前端)
3.构造新的链表,前后两部分链表结点交替添加到新链表中
4.构造完成
void reorderList(ListNode* head) { if (head == nullptr || head->next == nullptr) return; // 分割前后两部分 ListNode *slow = head; ListNode *fast = head; while (fast->next != nullptr && fast->next->next != nullptr) { slow = slow->next; fast = fast->next->next; } ListNode *head1 = head; ListNode *head2 = slow->next; slow->next = nullptr; head = head1; // 逆置链表 ListNode *tail2 = head2; head2 = head2->next; tail2->next = nullptr; while (head2 != nullptr) { ListNode *temp = head2->next; head2->next = tail2; tail2 = head2; head2 = temp; } // 交替构造新链表 head2 = tail2; while (head2 != nullptr) { ListNode *temp = head1->next; head1->next = head2; head1 = temp; ListNode *temp2 = head2->next; head2->next = head1; head2 = temp2; } }