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
原创粉丝点击