Leetcode——链表排序(归并)

1. 链表排序

Leetcode——链表排序(归并)_第1张图片

(1)暴力

class Solution {
    public ListNode sortList(ListNode head) {
        ListNode cur = head;
        int len = 0;
        while (cur != null) {
            cur = cur.next;
            len++;
        }

        cur = head;
        int index = 0;
        int[] a = new int[len];
        while (cur != null) {
            a[index++] = cur.val;
            cur = cur.next;
        }

        Arrays.sort(a);

        cur = head;
        index = 0;
        while (cur != null) {
            cur.val = a[index++];
            cur = cur.next;
        }
        return head;
    }
}

(2)归并

Leetcode——链表排序(归并)_第2张图片
Leetcode——链表排序(归并)_第3张图片
Leetcode——链表排序(归并)_第4张图片
Leetcode——链表排序(归并)_第5张图片

/**
 * 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) {
        // 1、递归结束条件
        if (head == null || head.next == null) {
            return head;
        }

        // 2、找到链表中间节点并断开链表 & 递归下探
        ListNode midNode = middleNode(head);
        ListNode rightHead = midNode.next;
        // 链表判断结束的标志:末尾节点.next==null
        midNode.next = null;		 
		
		 // 对左右半部分继续进行归并排序
        ListNode left = sortList(head);
        ListNode right = sortList(rightHead);

        // 3、当前层业务操作(合并有序链表)
        return mergeTwoLists(left, right);
    }
    
    //  找到链表中间节点(876. 链表的中间结点)
    private ListNode middleNode(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next.next;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        return slow;
    }

    // 合并两个有序链表(21. 合并两个有序链表)
    private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dumy = new ListNode(-1);
        ListNode cur = dumy;

        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }

            cur = cur.next;
        }

        cur.next = l1 != null ? l1 : l2;
        return dumy.next;
    }
}

你可能感兴趣的:(LeetCode,链表,leetcode,java)