对链表进行排序

1

public class SortLinkedList {

    // 方法:对链表进行排序
    public static ListNode sortList(ListNode head) {
        // 如果链表为空或只有一个节点,直接返回
        if (head == null || head.next == null) {
            return head;
        }

        // 使用快慢指针找到链表的中间节点
        ListNode mid = getMiddle(head);
        ListNode left = head;
        ListNode right = mid.next;
        mid.next = null;  // 断开链表

        // 递归地对左右两个部分进行排序
        left = sortList(left);
        right = sortList(right);

        // 合并排序后的两部分
        return merge(left, right);
    }

    // 辅助方法:找到链表的中间节点
    private static ListNode getMiddle(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head.next;

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

    // 辅助方法:合并两个有序链表
    private static ListNode merge(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

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

        if (l1 != null) {
            current.next = l1;
        } else {
            current.next = l2;
        }

        return dummy.next;
    }

 

 
posted @ 2024-08-14 09:56  抽象Java  阅读(1)  评论(0编辑  收藏  举报