您的位置:首页 > 其它

[LeetCode] Reorder List, Solution

2013-11-24 14:31 323 查看
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}
. [Thoughts] 目前想到的解法是,分三步来做: 1. 找出中间节点 2. 把中间节点之后的后半部分链表反序 3. 把前半部分链表及后半部分链表合并
 三步走解法

[code]     void reorderList(ListNode *head) {
if(head == NULL) return;
// find the median node
ListNode* fast = head;
ListNode* slow = head;
while(true)
{
fast = fast->next;
if(fast == NULL)
break;
fast = fast->next;
if(fast == NULL)
break;
slow = slow->next;
}

if(slow == NULL) return;

// reverse second half of link list
ListNode* cur = slow;
ListNode* pre = slow->next;
cur->next = NULL;
while(pre!=NULL)
{
ListNode* temp = pre->next;
pre->next = cur;
cur = pre;
pre = temp;
}

// merge two lists
ListNode* first = head;
ListNode* second = cur;

while(second!= NULL&& first!=NULL && first!=second)
{
ListNode* temp = second->next;
second->next = first->next;
first->next = second;
first = second->next;
second = temp;
}
}

应该有更漂亮的解法,还在思考中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: