143. Reorder List

本文介绍了一种链表重组算法,该算法将一个单向链表重新排序为特定形式,即首尾元素相邻,随后是剩余元素按原顺序配对。通过两步实现:首先找到中间节点并反转后半部分链表;然后交替地合并前半部分和反转后的后半部分。

Given a singly linked list LL0→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}.

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void reorderList(ListNode* head) {
12         if(head == NULL || head->next == NULL){
13             return;
14         }
15         
16         
17         
18         ListNode* fast = head;
19         ListNode* slow = head;
20         
21         while(fast->next != NULL && fast->next->next != NULL){
22             fast = fast->next->next;
23             slow = slow->next;
24         }
25         fast = slow->next;
26         slow->next = NULL;
27         
28         fast = ReverseList(fast);
29         
30         slow = head;
31         
32         while(slow){
33             if(fast != NULL){
34                 ListNode* n = slow->next;
35                 slow->next = fast;
36                 ListNode* nn = fast->next;
37                 fast->next = n;
38                 fast = nn;
39                 slow = n;
40             }else{
41                 break;
42             }
43         }
44     }
45     
46     
47     ListNode* ReverseList(ListNode* pHead){
48         ListNode* pReversedHead = NULL;
49         ListNode* pNode = pHead;
50         ListNode* pPrev = NULL;
51         
52         while(pNode != NULL){
53             ListNode* pNext = pNode->next;
54             
55             if(pNext == NULL){
56                 pReversedHead = pNode;
57             }
58             
59             pNode->next = pPrev;
60             pPrev = pNode;
61             pNode = pNext;
62         }
63         return pReversedHead;
64     }
65 };

 

转载于:https://www.cnblogs.com/sankexin/p/5867583.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值