【LeetCode】Reorder List
来源:互联网 发布:apache自定义404页面 编辑:程序博客网 时间:2024/05/16 17:45
题目
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}
.
先将链表从中间截成两部分(奇数的前半部分多一,注意截断后最后个元素指向null),然后翻转后半部分的,最后将两部分合并起来即可,代码如下:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public void reorderList(ListNode head) { if(head==null||head.next==null){ return; } ListNode fast=head; ListNode slow=head; while(fast!=null&&fast.next!=null&&fast.next.next!=null){ //要获取中间节点的前一个元素 fast=fast.next.next; slow=slow.next; } ListNode halfNode=slow.next; slow.next=null; //注意此处要将前半段最后一个元素指向null ListNode halfHead=null; while(halfNode!=null){ ListNode pre=halfNode; halfNode=halfNode.next; pre.next=halfHead; halfHead=pre; } ListNode cur=head; while(halfHead!=null){ ListNode pre=halfHead; halfHead=halfHead.next; pre.next=cur.next; cur.next=pre; cur=cur.next.next; //注意指针要指向隔一个节点 } }}
---EOF---
0 0
- [leetcode][list] Reorder List
- [leetcode][list] Reorder List
- Leetcode: Reorder List
- [LeetCode] Reorder List
- LeetCode题解:Reorder List
- Leetcode: Reorder List
- LeetCode:Reorder List
- leetcode之Reorder List
- Leetcode: Reorder List
- [LeetCode]Reorder List
- [LeetCode] Reorder List
- leetcode Reorder List
- LeetCode | Reorder List
- LeetCode Reorder List
- LeetCode 之 Reorder List
- Leetcode: Reorder List
- LeetCode OJ:Reorder List
- Reorder List (LeetCode)
- C# RSA和Java RSA互通
- 【PyQt4 实例29】利用QDataStream对文件进行存取
- WPF Silverlight 附加属性(AttachedProperty)
- Android中的Shape使用总结—圆角的按钮
- 排序算法
- 【LeetCode】Reorder List
- NSThread详解
- 《网络协议》TCP 四种定时器
- QB/T 2155-2010拉杆箱检测
- 时钟周期 指令周期 机器周期的理解
- avalon 之 watch 一两事
- HDU~1879~继续畅通工程
- NSObject类别-NSThreadPerformAdditions
- Python&Pycharm&Django安装