题目: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}.
解析:将链表从中间断开,然后将后半段链表逆序,最后将前半段链表以及逆过序后的后半段链表合并在一起
解题代码如下:
class Solution {
public:
void reorderList(ListNode *head) {
if (!head || !head -> next) return;
//计算链表总长度
int len = 0;
ListNode *cur = head;
while (cur != nullptr) {
++len;
cur = cur -> next;
}
int mid = len % 2 != 0 ? len / 2 + 1 : len / 2;
ListNode* mid_ptr = head;
for (int i = 0; i != mid - 1; ++i)
mid_ptr = mid_ptr -> next;
// 从中间将原先链表分成两个链表
ListNode* head2 = mid_ptr -> next;
mid_ptr -> next = nullptr;
// 将后半段链表逆序
head2 = reverseList(head2);
//将这两个链表再次合并成一个链表
ListNode *cur1 = head, *cur2 = head2;
while (cur2 != nullptr) {
ListNode* tmp = cur2 -> next;
cur2 -> next = cur1 -> next;
cur1 -> next = cur2;
cur1 = cur1 -> next -> next;
cur2 = tmp;
}
}
private:
ListNode* reverseList(ListNode* head) {
if (!head) return head;
ListNode dummy{-1};
dummy.next = head;
ListNode* cur = head;
while (cur -> next != nullptr) {
ListNode* tmp = cur -> next;
cur -> next = tmp -> next;
tmp -> next = dummy.next;
dummy.next = tmp;
}
return head;
}
};