Reorder List
来源:互联网 发布:淘宝领的话费券在哪 编辑:程序博客网 时间:2024/06/05 07:34
链表基本功
1. 找到中点;
2. 对链表后半部分反转;
3. 将前半部分和后半部分拼接
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public void reorderList(ListNode head) { if (head == null || head.next == null) {return;}ListNode fn = head.next.next, sn = head;while (fn != null && fn.next != null) {sn = sn.next;fn = fn.next.next;}if (fn != null) {sn = sn.next;}ListNode rightHalf = reverse(sn.next);sn.next = null;while (rightHalf != null) {ListNode temp1 = head.next;head.next = rightHalf;ListNode temp2 = rightHalf.next;rightHalf.next = temp1;head = temp1;rightHalf = temp2;} }private ListNode reverse(ListNode node) {ListNode prev = null;while (node != null) {ListNode temp = node.next;node.next= prev;prev = node;node = temp;}return prev;}}
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}
.
0 0
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- 推荐算法:基于图的算法:基于路相似度_续
- Regional 2015 - Asia EC Final - C Suffixes and Palindromes
- osgi + felix example1编写
- C programming-------exit() 函数
- 002——Filter解决乱码问题
- Reorder List
- can I read/write the routing table in C without using system() command?
- HDU 4825 Xor Sum
- Jquery+html+css实现广告条
- Android 自定义属性写法
- 【SpringMVC学习07】SpringMVC中的统一异常处理
- VR开发的24个技巧
- 移动开发--优秀博客收集(持续更新)
- Qt中的QAction