您的位置:首页 > 其它

【LeetCode】Reorder List

2014-08-27 23:34 197 查看
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 || !head->next->next) {
return;
}

// find the last and median nodes
ListNode *slow, *fast;
slow = fast = head;
while (fast != NULL) {
if (fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
} else {
break;
}
}

ListNode *prev, *curr, *succ;

prev = slow->next;
curr = prev->next;
succ = curr ? curr->next : NULL;

prev->next = NULL;
slow->next = NULL;

// reverse list
while (succ != NULL) {
curr->next = prev;
prev = curr;
curr = succ;
succ = succ->next;
}

// reverse the last two nodes
if (curr == NULL) { // there only 1 node in list.
curr = prev;
} else {
curr->next = prev;
}

ListNode *head_1 = head->next;
ListNode *head_2 = curr;
ListNode *tail = head;

// merge two lists
while (head_1 && head_2) {
tail->next = head_2; head_2 = head_2->next;
tail = tail->next;

tail->next = head_1; head_1 = head_1->next;
tail = tail->next;
}

tail->next = head_1 ? head_1 : (head_2 ? head_2 : NULL);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: