1. 程式人生 > 其它 >【每日一題】【歸併排序】2021年12月20日-148. 排序連結串列

【每日一題】【歸併排序】2021年12月20日-148. 排序連結串列

給你連結串列的頭結點 head ,請將其按 升序 排列並返回 排序後的連結串列 。

進階:

你可以在 O(n log n) 時間複雜度和常數級空間複雜度下,對連結串列進行排序嗎?

答案:

/**
 * 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) { return head == null ? null : mergeSort(head); } public ListNode mergeSort(ListNode head) { if(head.next == null) { return head; } ListNode q = head, p = head, pre = null; while
(q != null && q.next != null) { pre = p; p = p.next; q= q.next.next; } pre.next = null; ListNode l = mergeSort(head); ListNode r = mergeSort(p); return merge(l, r); } public ListNode merge(ListNode l, ListNode r) { ListNode dummy
= new ListNode(0); ListNode cur = dummy; while(l != null && r != null) { if(l.val <= r.val) { cur.next = l; cur = cur.next; l = l.next; } else { cur.next = r; cur = cur.next; r = r.next; } } if(l != null) { cur.next = l; } if(r != null) { cur.next = r; } return dummy.next; } }

本文來自部落格園,作者:劉金輝,轉載請註明原文連結:https://www.cnblogs.com/liujinhui/p/15712729.html