Leetcode: Reorder List
来源:互联网 发布:淘宝上怎么好评改差评 编辑:程序博客网 时间:2024/06/02 02:22
url :
https://leetcode.com/problems/reorder-list/description/
描述
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}.
代码
class Solution { public void reorderList(ListNode head) { if(head == null) return; ListNode p = head; int count = 0; while(p!=null){ p=p.next; count++; } ListNode[] points = new ListNode[count]; p = head; count = 0; while(p!=null){ points[count++] = p; p=p.next; } int i = 0, j = count-1; while(i < j) { points[i].next = points[j]; points[j--].next = points[++i]; } points[i].next = null; } }
上面的方法总是感觉有点不正宗,下面给出链表的操作,大概就是把链表的后半段作为单独的一段链表,并进行反转,然后在把两个合成一个就行啦,代码如下:
public void reorderList3(ListNode head) { if(head==null) return; ListNode fast = head, slow = head; while(fast!=null && fast.next!=null){ fast = fast.next.next; if(fast!=null){ slow = slow.next; } } ListNode pre = null; ListNode p = slow.next; ListNode post = p==null ? null : p.next; while(post!=null){ p.next = pre; pre = p; p=post; post = post.next; } if(p!=null) p.next = pre; slow.next = null; ListNode h1 = head; ListNode h2 = head.next; ListNode m = p; while(h1!=null && m!=null) { h1.next = m; m = m.next; h1 = h1.next; h1.next = h2; h2 = h2 == null? null : h2.next; h1 = h1.next; } }
阅读全文
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)
- 字符游戏-智能蛇
- springboot+jsp返回404原因
- poi读取word
- 离线地图开发
- OSGI入门实例讲解(一)
- Leetcode: Reorder List
- mysql数据库的导入和导出
- 20171221_C语言学习
- Shuttle安装以及配置简介
- XRecyclerView的简单使用与图片拉动字体缩放效果的实现
- IT风投!
- sql server和access的机制有很大的不同
- 如何1秒钟让程序员抖腿?教你10个方法!
- 服务端I/O性能大比拼:Node、PHP、Java、Go