【归并排序】148. 排序链表

【归并排序】148. 排序链表

解题思路

  • 链表的归并排序
  • 链表自顶向下归并排序
  • 使用快慢指针找到链表的中点,快指针每次移动两步,慢指针每次移动一步
  • 对两个子链表分别进行排序
  • 将两个排序之后的链表进行合并,得到完整的排序之后的链表
/**
 * 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,ListNode tail){
    
    
        if(head == null){
    
    
            return head;
        }

        if(head.next == tail){
    
    
            head.next = null;
            return head;
        }

        // 上面两个是处理单个节点的情况

        // 找到链表的中点  然后进行分割 使用快慢指针方法
        ListNode slow = head,fast = head;

        // 慢指针每次走一步  快指针一次走两步
        while(fast != tail){
    
    
            slow = slow.next;
            fast = fast.next;

            if(fast != tail){
    
    
                fast = fast.next;
            }
        }

        ListNode mid = slow;// slow指向链表中点
        ListNode list1 = sortList(head,mid);
        ListNode list2 = sortList(mid,tail);
        ListNode sorted = merge(list1,list2);// 合并链表
        return sorted;
    }

    public ListNode merge(ListNode head1,ListNode head2){
    
    
        // 创建哑结点
        ListNode dummyHead = new ListNode(0);
        ListNode temp = dummyHead,temp1 = head1,temp2 = head2;

        // 将两个子链表合并到一个大的链表  然后返回
        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 = temp.next;
        }

        if(temp1 != null){
    
    
            temp.next = temp1;
        }else if(temp2 != null){
    
    
            temp.next = temp2;
        }

        return dummyHead.next;


    }

    public ListNode sortList(ListNode head) {
    
    
        // 使用归并排序

        return sortList(head,null);



        // 

    }
}

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/131710602