Leetcode: reorder-list
来源:互联网 发布:sizeof数组 编辑:程序博客网 时间:2024/06/10 02:19
题目:
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}.
分析:
这道题可以分三个步骤来解决。一、找到原链表的中间位置,以这个中间位置为基准将链表分为两段;二、将处在后半段的链表进行反转;三、将两个链表进行融合。
具体的代码如下:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public static void reorderList(ListNode head) { if (head == null || head.next == null) return ; ListNode mid = findMiddle(head); ListNode aft = mid.next; mid.next = null; ListNode pre = head; aft = reverse(aft); merge(pre, aft); } public static ListNode reverse(ListNode aft){ ListNode l1 = aft; ListNode l2 = aft.next; while(l2 != null){ ListNode tmp = l2.next; l2.next = l1; l1 = l2; l2 = tmp; } aft.next = null; return l1; } public static void merge(ListNode pre, ListNode aft){ while (aft != null){ ListNode aftN = aft.next; ListNode preN = pre.next; pre.next = aft; aft.next = preN; aft = aftN; pre = preN; } } public static ListNode findMiddle(ListNode head){ ListNode slow = head; ListNode fast = head; while(fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } return slow; }}
阅读全文
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)
- App开放接口api安全性—Token签名sign的设计与实现
- 纪念:毕业不到一年 裸辞了
- 拼接option,并给其中一个option赋值
- 打开远程桌面命令
- 银行VIP客户人脸识别系统--基于深度学习
- Leetcode: reorder-list
- opencv读取文件夹中的图片
- Struts与Servlet遇到的404问题
- Android_动画:Interpolator
- Spring线程池ThreadPoolTaskExecutor配置及详情
- log4j配置详解
- Linux7.3下MySQL(5.7)yum安装步骤
- 傅里叶变换
- https安全在哪里,原理是什么?