Sort List ---LeetCode
来源:互联网 发布:c语言函数调用过程 编辑:程序博客网 时间:2024/06/06 19:38
https://leetcode.com/problems/sort-list/
解题思路:
这里选择归并排序,顺便能用到 Merge Two Sorted List 的解法。
归并排序三个步骤:
- 找到链表中点
- 对左右两边链表进行递归
- 最后归并两边链表
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */public class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) return head; ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } ListNode head1 = head; ListNode head2 = slow.next; slow.next = null; head1 = sortList(head1); head2 = sortList(head2); return mergeTwoLists(head1, head2); } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null && l2 == null) return null; ListNode dummy = new ListNode(0); ListNode prev = dummy; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { prev.next = l1; l1 = l1.next; } else { prev.next = l2; l2 = l2.next; } prev = prev.next; } if (l1 != null) prev.next = l1; if (l2 != null) prev.next = l2; return dummy.next; }}
0 0
- [leetcode][list][sort] Sort List
- Insertion Sort List | leetcode
- Leetcode: Insertion Sort List
- [LeetCode] Insertion Sort List
- Leetcode: Insertion Sort List
- Leetcode: Sort List
- Sort List | leetcode
- leetcode-Sort List
- leetcode-Insertion Sort List
- LeetCode题解:Sort List
- leetcode 134: Sort List
- [LeetCode]Sort List
- [LeetCode]Insertion Sort List
- [LeetCode] Sort List
- 【LeetCode】Insertion Sort List
- leetCode - Sort List
- LeetCode | Insertion Sort List
- LeetCode - Insertion Sort List
- 问题-2011-11-24:“const int vc_attributes::Pre::wchar_t”: 重定义
- Codeforces Round #381 (Div. 2) A. Alyona and copybooks
- JAVASE中那些新手常见却不易找的错误
- Android性能优化——渲染
- 浮点类型的存储方式
- Sort List ---LeetCode
- 让 Caps Lock 键变得实用
- pat甲1021.Deepest Root(简单dfs)
- Java基础I/O流(一)
- 数据库SQL优化大总结之
- 反射、类加载
- Ubuntu 安装JDK1.8
- android 中保证进程不被杀死
- Mysql启动不了报错Timeout error 磁盘满