leetcode 148. 排序链表(归并排序)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 148. 排序链表(归并排序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給你鏈表的頭結點 head ,請將其按 升序 排列并返回 排序后的鏈表 。
進階:
你可以在 O(n log n) 時間復雜度和常數級空間復雜度下,對鏈表進行排序嗎?
示例 1:
輸入: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 sortList(ListNode head) {return sort(head);}public ListNode sort(ListNode head) {ListNode start=head,slow=head,fast=head,pre=head;while (fast!=null&&fast.next!=null)//雙指針找中點{pre=slow;fast=fast.next.next;slow=slow.next;}if(slow!=start){pre.next=null;return merge(sort(start),sort(slow));//合并鏈表}return slow;}public ListNode merge(ListNode head,ListNode slow) {//將兩個鏈表合并ListNode dumpy=new ListNode(-1),cur=dumpy;while (head!=null&&slow!=null){if(head.val<slow.val){dumpy.next=head;dumpy=dumpy.next;head=head.next;dumpy.next=null;}else {dumpy.next=slow;dumpy=dumpy.next;slow=slow.next;dumpy.next=null;}}if(head!=null)dumpy.next=head;else if(slow!=null)dumpy.next=slow;else dumpy.next=null;return cur.next;} }總結
以上是生活随笔為你收集整理的leetcode 148. 排序链表(归并排序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到鱼咬自己的手什么预兆
- 下一篇: 梦到家里人被杀是什么征兆