给定单链表L:L0→L1→...→Ln-1→Ln, 重新排序:L0→Ln→L1→Ln-1→L2→Ln-2→...

时间:2021-10-04 00:13:04

本题源自leetcode  143

----------------------------------------------------------------------------

思路1:用快慢指针找到中节点,然后反转后半部分链表。然后俩个链表交叉插入

代码:

void reorderList(ListNode* head) {
if (!head || !head->next)
return;

// find the middle node: O(n)
ListNode *slow = head, *fast = head;
while (fast && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}

// cut from the middle and reverse the second half: O(n)
ListNode *head2 = slow->next;
slow->next = NULL;

ListNode *q = head2->next;
head2->next = NULL;
while (q) {
ListNode *qNext = q->next;
q->next = head2;
head2 = q;
q = qNext;
}
ListNode* p = head;
// merge two lists: O(n)
for (q = head2; p; ) {
auto t = p->next;
p->next = q;
p = p->next;
q = t;
}
/*
slow->next = reverse(slow->next);
ListNode* q = slow->next;
//reverse(slow->next);
while(p != slow && q ){
ListNode * qNext = q->next;
q->next = p->next;
p->next = q;
p = q->next;
q = qNext;
}
*/
}

代码2:

 void reorderList(ListNode* head) {
if (!head || !head->next)
return;

// find the middle node: O(n)
ListNode *slow = head, *fast = head;
while (fast && fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}

// cut from the middle and reverse the second half: O(n)
ListNode *head2 = reverse(slow->next);
slow->next = NULL;
ListNode* p = head, *q = head2;
/*
// merge two lists: O(n)
for (; p; ) {
auto t = p->next;
p->next = q;
p = p->next;
q = t;
}
*/
//reverse(slow->next);
while(p && q ){
ListNode * qNext = q->next;
q->next = p->next;
p->next = q;
p = q->next;
q = qNext;
}
}

ListNode* reverse(ListNode* root){
if(!root)
return NULL;
ListNode* pre = NULL;
ListNode* p = root;
ListNode* pNext = NULL;
while(p){
pNext = p->next;
p->next = pre;
pre = p;
p = pNext;
}
return pre;
}