leetcode reorder-list(java实现)
来源:互联网 发布:访问网络电脑需要密码 编辑:程序博客网 时间:2024/05/16 04:49
原题:
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}.
分析:
思路是将链表分为前后两部分,将后面的部分逆置后依次对应插入。具体实现中先采用快慢指针找到链表的中点,将链表分为两部分。我的代码中用快慢指针找中点时,没有做额外的处理,合并列表时也没有多余的操作,所以在最前面需要将只有两个元素(即head.next.next==null)的情况提前考虑,否则会报错。
代码如下:
public class Solution { public void reorderList(ListNode head) { if(head==null || head.next==null || head.next.next==null) return ; ListNode head2 = null; ListNode slow = head; ListNode fast = head; while(fast!=null && fast.next!=null){ slow = slow.next; fast = fast.next.next; if(slow == fast){ break; } } head2 = reverseList(slow.next); slow.next = null; while(head!=null && head2!=null){ ListNode p1 = head.next; ListNode p2 = head2.next; head.next = head2; head2.next = p1; head = p1; head2 = p2; } } public static ListNode reverseList(ListNode head){ ListNode cur = null; ListNode p = head.next; if(p == null) return head; cur = head; cur.next = null; while(p!=null){ ListNode tmp = cur; cur = p; p = p.next; cur.next = tmp; } return cur; }}
0 0
- leetcode reorder-list(java实现)
- LeetCode:Reorder List C++与Java实现
- [Leetcode] Reorder List (Java)
- Reorder List leetcode java
- ReOrder List java实现
- LeetCode Reorder List Java版本
- [LeetCode] 143. Reorder List java
- LeetCode(143) Reorder List
- leetcode: Reorder List 的Python实现
- [leetcode][list] Reorder List
- [leetcode][list] Reorder List
- <LeetCode(Java版)>Reorder List
- [LeetCode]--143. Reorder List(Python + Java)
- leetcode oj java 143. Reorder List
- LeetCode 题解(142): Reorder List
- leetcode系列(71)Reorder List
- Leetcode: Reorder List
- [LeetCode] Reorder List
- [玲珑杯#Round8] XJT Love Strings KMP+树上倍增
- java web给手机端写接口HttpServletRequest ,HttpServletResponse
- Arpa's weak amphitheater and Mehrdad's valuable Hoses CodeForces - 742D
- AVR_Timer
- Python基础_1
- leetcode reorder-list(java实现)
- 重点:linux执行操作命令
- 欢迎使用CSDN-markdown编辑器
- redis 管理工具
- 后缀数组
- Android之使用JavaWeb项目作为后台的实现
- 关于linux-Centos 7下mysql 5.7.9的rpm包的安装方式
- centos7.2下安装mysql5.7,使用rpm包安装
- 理解和实现KMP算法