LeetCode-链表排序

108 阅读1分钟

算法记录

LeetCode 题目:

  给定链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。


说明

一、题目

  输入:head = [4,2,1,3]   输出:[1,2,3,4]

二、分析

  • 排序的方法有很多,我们这里使用归并作为排序算法。
  • 需要注意的是链表中点的寻找。
class Solution {
    public ListNode merge(ListNode h1, ListNode h2) {
        ListNode ans = new ListNode(), temp = ans;
        while(h1 != null || h2 != null) {
            if(h2 == null || (h1 != null && h1.val < h2.val)) {
                temp.next = h1;
                h1 = h1.next;
                temp = temp.next;
            } else {
                temp.next = h2;
                h2 = h2.next;
                temp = temp.next;
            }
        }
        return ans.next;
    }

    public ListNode sort(ListNode head) {
        if(head == null || head.next == null) return head;
        ListNode slow = head, fast = head.next;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        ListNode h2 = slow.next;
        slow.next = null;
        slow = sort(head);
        fast = sort(h2);
        return merge(slow, fast);
    }
    public ListNode sortList(ListNode head) {
        return sort(head);
    }   
}

总结

熟悉归并算法对于链表结构的使用。