LeetCode: Reorder List

LeetCode: Reorder List

Given a singly linked list L: L0L1→…→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}.

地址:https://oj.leetcode.com/problems/reorder-list/

算法:先把链表从中间节点分成两段,然后将后半部分的链表逆置,最后在将后半部分的链表按题目的要求插入原链表中。代码:

 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         int num_node = 0;
13         ListNode *p = head;
14         while(p){
15             ++num_node;
16             p = p->next;
17         }
18         int half_num_node = (num_node + 1) / 2;
19         p = head;
20         ListNode *pre = NULL;
21         for (int i = 0; i < half_num_node; ++i){
22             pre = p;
23             p = p->next;
24         }
25         if(pre) pre->next = NULL;
26         pre = NULL;
27         ListNode *half_head = NULL;
28         while (p){
29            pre = p;
30            p = p->next;
31            pre->next = half_head;
32            half_head = pre;
33         }
34         p = head;
35         while(half_head){
36             pre = half_head;
37             half_head = half_head->next;
38             pre->next = p->next;
39             p->next = pre;
40             p = p->next->next;
41         }
42     }
43 };

 

posted on 2014-08-01 10:21 Boostable 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/boostable/p/leetcode_reorder_list.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值