LeetCode Sort List
来源:互联网 发布:矩阵各元素之和叫什么 编辑:程序博客网 时间:2024/04/28 07:31
题意:给定一个list的节点,对它进行排序
解法:归并排序咯~直接上码
<span style="font-size:18px;">class ListNode {int val;ListNode next;ListNode(int x) {val = x;next = null;}}public class Solution {public ListNode sortList(ListNode head) {if (head == null || head.next == null)return head;ListNode h1 = head;int len = 0;ListNode t1 = h1, t2;while (t1 != null) {len++;t1 = t1.next;}if (len == 0 || len == 1) {return h1;}t1 = h1;for (int i = 1; i < len / 2; i++)t1 = t1.next;ListNode h2 = t1.next;t1.next = null;h1 = sortList(h1);h2 = sortList(h2);t1 = h1;t2 = h2;ListNode current;if (t1.val < t2.val) {head = t1;t1 = t1.next;} else {head = t2;t2 = t2.next;}current = head;while (t1 != null && t2 != null) {if (t1.val < t2.val) {current.next = t1;current = current.next;t1 = t1.next;} else {current.next = t2;current = current.next;t2 = t2.next;}}if (t1 != null) {current.next = t1;} else {current.next = t2;}return head;}public static void main(String[] args) {ListNode h1 = new ListNode(20);ListNode h2 = new ListNode(5);ListNode h3 = new ListNode(4);ListNode h4 = new ListNode(1);ListNode h5 = new ListNode(3);h1.next = h2;h2.next = h3;h3.next = h4;h4.next = h5;Solution s = new Solution();ListNode h = s.sortList(h1);s.print(h);}public void print(ListNode h) {while (h != null) {System.out.print(h.val + " ");h = h.next;}System.out.println();}}</span>
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
- js压缩原理
- Android研究院之应用开发线程池的经典使用(二十九)
- VC嵌套VC导致显示位置偏移的解决方法
- 三种最简单基础的排序 选择排序 冒泡排序 直接插入排序 运用了函数指针数组
- 移植开源QT软件-SameGame
- LeetCode Sort List
- Cannot convert value '0000-00-00 00:00:00' from column 1 to TIMESTAMP
- 英语简单句、并列句、复合句
- 简明vim练级攻略
- android shape的使用
- CentOS yum 源的配置与使用
- 芯客-Rayeager PX2应用之USB摄像头---UVC摄像头篇
- 设置控件单个或某几个角为圆角的实现
- UVa 1339 简单加密(encrypt)