LeetCode 143. Reorder List
2016-03-22 23:00
399 查看
题目描述:
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}.
解题思路:
这是一个很常规的题目, 拿到这道题目只需要将链表分割成前后两段,可以借助快慢指针的做法, 然后将后面一个链表逆置, 再按照指定的次序排序就可以了。
下面是代码:
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}.
解题思路:
这是一个很常规的题目, 拿到这道题目只需要将链表分割成前后两段,可以借助快慢指针的做法, 然后将后面一个链表逆置, 再按照指定的次序排序就可以了。
下面是代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: void reorderList(ListNode* head) { // 先找到链表的中心位置, 切开 ListNode myhead(0); myhead.next = head; ListNode * p1 = &myhead, *p2 = &myhead; while (p1 && p1->next){ p1 = p1->next->next; p2 = p2->next; } ListNode * pNext = p2->next; // 将后面一部分链表切开 ListNode myhead2(0); p2->next = nullptr; myhead2.next = pNext; // 将链表2 逆置 ListNode * pCur = myhead2.next; ListNode * pPre = nullptr; while (pCur){ ListNode * pNext = pCur->next; pCur->next = pPre; pPre = pCur; pCur = pNext; } myhead2.next = pPre; // 归并排序, 因为p1 >= p2 p1 = myhead.next; p2 = myhead2.next; ListNode res(0); ListNode * pres = &res; while (p1){ pres->next = p1; p1 = p1->next; pres = pres->next; pres->next = nullptr; if (p2){ pres->next = p2; p2 = p2->next; pres = pres->next; pres->next = nullptr; } } } };
相关文章推荐
- lua gc 优化方案
- Android数据库框架
- 无线AP和无线路由器区别
- Spring IOC
- angular-输入验证
- 无线AP和无线路由器区别
- 分析与设计数据库模型的简单过程
- 【真题索引】2016/03/22知识点整理
- [Java] 实验4参考代码
- eclipse 安装maven 插件
- 网络基本功(1)--网络传输
- C++11 right value
- 指针数组、数组指针、二维数组动态分配内存
- 嵌入式Linux UDP通信:服务端程序
- Oracle数据库学习(一)--数据库原理及SQL
- 代码规范_3:c++ _异常
- angular-模块Module
- Codeves 2800 送外卖 状态压缩DP+floyd
- SQL Server 2008 R2主数据服务安装
- 多个进程能否监听同一个端口号?