[Leetcode] #143 Reorder List

来源:互联网 发布:淘宝客复制别人的商品 编辑:程序博客网 时间:2024/05/16 08:45

Discription:

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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}.

Solution:

void reorderList(ListNode* head) {if (head == NULL || head->next == NULL) return ;ListNode *pslow = head;ListNode *pfast = head;while (pfast->next && pfast->next->next){pslow = pslow->next;pfast = pfast->next->next;}ListNode *last= pslow->next;pslow->next = NULL;ListNode *pre = NULL;while (last){ListNode *post = last->next;last->next = pre;pre = last;last = post;}ListNode *node1 = head, *node2 = pre;while (node2 != NULL){ListNode *tmp1 = node1->next;ListNode *tmp2 = node2->next;node1->next = node2;node2->next = tmp1;node1 = tmp1;node2 = tmp2;}}

附:Leetcode源代码见我的GitHub  

0 0
原创粉丝点击