Reorder List (Java)
来源:互联网 发布:未来教育二级vb序列号 编辑:程序博客网 时间:2024/05/29 13:31
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}
.
把找到的中位数的下一个结点及之后的链表逆序,然后插入到前面的链表中。
Source
/** * 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 p = head, q = head; while(q.next != null && q.next.next != null){//遍历一遍找到中间结点的方法就是一个指针走 一步另一个走两步 p = p.next; q = q.next.next; } q = p.next; p.next = null; //*** ListNode ppre = null; ListNode ppost; //ppre指向p的前一个结点 ppost指向p的下一个结点 while(q != null){//链表逆置就是把链表指针顺序换个方向即可 ppost = q.next; q.next = ppre; ppre = q; q = ppost; } q = ppre; //此时是最后一个结点是头结点 p = head; ListNode temp1, temp2; while(p != null && q != null){ temp1 = p.next; temp2 = q.next; q.next = temp1; p.next = q; p = temp1; q = temp2; } }}
Test
public static void main(String[] args){ ListNode a = new ListNode(1); a.next = new ListNode(2); a.next.next = new ListNode(3); a.next.next.next = new ListNode(4); a.next.next.next.next = new ListNode(5); new Solution().reorderList(a); while(a != null){ System.out.println(a.val); a = a.next; } }
0 0
- [Leetcode] Reorder List (Java)
- ReOrder List java实现
- Reorder List Java
- Reorder List (Java)
- reorder-list java
- Reorder List leetcode java
- reorder-list Java code
- LeetCode Reorder List Java版本
- [LeetCode] 143. Reorder List java
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- Reorder List
- iOS中对UITableView中的cell设置自动适应行高
- margin、padding、tint、hint不想再混乱了
- java多线程总结 (一)
- 1. (寄存器)STM32学习——概述
- JQuery AJAX $.get()方法
- Reorder List (Java)
- 20150101-回顾2014,展望2015
- 文件目录操作二----------目录创建删除显示
- Ubuntu 12.04安装TLF-SOFT-Mathworks.Matlab.R2012a.UNIX.ISO-TBE.iso
- Integer to Roman
- github for windows 2.0版本使用教程
- java中读取Properties文件的六种方法
- 实变函数-上下限集/极限
- word毕设论文制作——封面(一)