148. 排序链表 + 归并排序

148. 排序链表

LeetCode_148

题目描述

题解分析

  1. 可以利用归并排序的思想对链表进行排序
  2. 要利用归并排序,首先就要得到中间结点,这个可以利用快慢指针来实现。
  3. 剩下的就是链表合并的问题,具体可以参考:https://www.cnblogs.com/GarrettWale/p/14514211.html

代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode sortList(ListNode head) {
        return sortList(head, null);
    }
    public ListNode sortList(ListNode head, ListNode tail){
        if(head == null)
            return head;
        if(head.next == tail){
            head.next = null;//这里是保证链表被分割为以null为next的结点
            return head;
        }
        //使用快慢指针找到中间结点
        ListNode slow = head, quick = head;
        while(quick != tail){
            slow = slow.next;
            quick = quick.next;
            if(quick != tail)
                quick = quick.next;
        }
        ListNode list1 = sortList(head, slow);
        ListNode list2 = sortList(slow, tail);
        return merge(list1, list2);
    }
    public ListNode merge(ListNode list1, ListNode list2){
        ListNode newHead = new ListNode();
        ListNode temp = newHead, temp1 = list1, temp2 = list2;
        while(temp1 != null && temp2 != null){
            if(temp1.val <= temp2.val){
                temp.next = temp1;
                temp1 = temp1.next;
            }else{
                temp.next = temp2;
                temp2 = temp2.next;
            }
            temp = temp.next;
        }
        if(temp1 != null)
            temp.next = temp1;
        else if(temp2 != null)
            temp.next = temp2;
        return newHead.next;//注意这里不能返回temp.next,否则结果不正确
    }
}

posted @ 2021-03-10 21:13  Garrett_Wale  阅读(59)  评论(0编辑  收藏  举报