reorder-list
来源:互联网 发布:人工智能战机 编辑:程序博客网 时间:2024/06/13 23:18
题目描述:
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}.
本题的想法就是先将列表平分成两份,后一份逆序,然后再将两段拼接在一起,逆序可用头插法实现。
代码实现:
package leetcoder;class ListNode2 {int val;ListNode2 next;ListNode2(int x) {val = x;next = null;}}public class ReorderList { public static void reorderList(ListNode2 head) { //链表为空或只有一个结点,直接返回 if(head == null || head.next == null) return; //把链表从中间分成两段 ListNode2 fast = head.next; ListNode2 slow = head; while(fast!=null && fast.next != null){ fast = fast.next.next; slow = slow.next; } ListNode2 p = slow.next;//P指向第二段链表的开头 slow.next = null; //使用头插法将第二段链表翻转 ListNode2 pPre = null;//pPre始终指向链表的开始节点 ListNode2 pSuf = p.next;//pSuf指向待插入的结点 while(p != null){ pSuf = p.next; p.next = pPre; pPre = p; p = pSuf; } //合并两个单链表 ListNode2 l1 = head; ListNode2 l2 = pPre; while(l1 != null && l2 != null){ ListNode2 l1Next = l1.next; ListNode2 l2Next = l2.next; l1.next = l2; l2.next = l1Next; l1 = l1Next; l2 = l2Next; } } public static void main(String[] args) {ListNode2 n1 = new ListNode2(1);ListNode2 n2 = new ListNode2(2);ListNode2 n3 = new ListNode2(3);ListNode2 n4 = new ListNode2(4);n1.next = n2;n2.next = n3;n3.next = n4;n4.next = null;reorderList(n1);ListNode2 p = n1;while(p != null){System.out.println(p.val);p = p.next;}}}
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
- Leetcode:64. Minimum Path Sum
- 《利用Python 进行数据分析》 - 笔记(2)
- [系统运维]Supervisord安装和启动程序
- 待解决问题——prime——内存超限
- 火焰检测的一些名词解释
- reorder-list
- C#序列化和反序列化综合案例
- HDOJ1020
- 部分背包问题
- leetcode——109——Convert Sorted List to Binary Search Tree
- hdu2147——kiki's game(博弈论)
- hibernate.cfg.xml配置文件的解释
- 【LeetCode】Contains Duplicate 解题报告
- 乔帮主告诉你什么是面向对象