热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

LeetCode解题报告:ReorderList

ReorderListGivenasinglylinkedlistL:L0→L1→…→Ln-1→Ln,reorderitto:L0→Ln→L1→Ln-1→L2→Ln-2→…Youm

Reorder List

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→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}.

思路:

1.利用快慢两个指针将链表一分为二;

2.针对第二个子链表求倒序;

3.利用merge思想将两个子链表合并。

代码:

,,
 1 public class ReorderSingleList {
 2     /**
 3      * Definition for singly-linked list. class ListNode { int val; ListNode
 4      * next; ListNode(int x) { val = x; next = null; } }
 5      */
 6     public void reorderList(ListNode head) {
 7         if (head == null || (head.next == null)) {
 8             return;
 9         }
10         // fast and slow point find the mid position.
11         ListNode fast = head;
12         ListNode slow = head;
13         while ((fast != null) && (fast.next != null)) {
14             fast = fast.next.next;
15             slow = slow.next;
16         }
17 
18         // reverse the last second list.
19         ListNode headnode = new ListNode(-1);
20         headnode.next = slow;
21         ListNode temp = headnode.next;
22         while (temp.next != null) {
23             ListNode insert = temp.next;
24             ListNode currNext = insert.next;
25             insert.next = headnode.next;
26             headnode.next = insert;
27             temp.next = currNext;
28         }
29 
30         // merge insert
31         ListNode firstcur = head;
32         ListNode secOndcur= headnode.next;
33         while (firstcur != slow && (secondcur != slow)) {// at first,I make a mistake in here;
34             ListNode firstnex = firstcur.next;
35             ListNode secOndnex= secondcur.next;
36             firstcur.next = secondcur;
37             secondcur.next = firstnex;
38             firstcur = firstnex;
39             secOndcur= secondnex;
40         }
41     }
42 
43     public static void main(String[] args) {
44         ListNode t5 = new ListNode(5);
45         ListNode t4 = new ListNode(4, t5);
46         ListNode t3 = new ListNode(3, t4);
47         ListNode t2 = new ListNode(2, t3);
48         ListNode t1 = new ListNode(1, t2);
49         new ReorderSingleList().reorderList(t1);
50         System.out.println(t1);
51     }
52 
53 }
View Code

LeetCode解题报告:Reorder List,,

LeetCode解题报告:Reorder List


推荐阅读
author-avatar
月满西楼2502890155
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有