剑指 Offer II 077. 链表排序

算法记录

LeetCode 题目:

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



说明

一、题目

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

二、分析

  • 排序的方法有很多,我们这里使用归并作为排序算法。
  • 需要注意的是链表中点的寻找。
/**
 * 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 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);
    }   
}

总结

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

Guess you like

Origin blog.csdn.net/MTYSYS19990212/article/details/120394952