[LeetCode] 148. Sort List
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 148. Sort List相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/sort-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 mid = findMiddle(head); ListNode head2 = sortList(mid.next); mid.next = null; ListNode head1 = sortList(head); return merge(head1, head2); } public ListNode merge(ListNode head1, ListNode head2) { ListNode dummy = new ListNode(-1); ListNode head = dummy; while (head1 != null && head2 != null) { if (head1.val < head2.val) { head.next = head1; head1 = head1.next; } else { head.next = head2; head2 = head2.next; } head = head.next; } while (head1 != null) { head.next = head1; head1 = head1.next; head = head.next; } while (head2 != null) { head.next = head2; head2 = head2.next; head = head.next; } return dummy.next; } public ListNode findMiddle(ListNode head) { ListNode fast = head; ListNode slow = head; while (fast.next != null && fast.next.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } }
以上是关于[LeetCode] 148. Sort List的主要内容,如果未能解决你的问题,请参考以下文章