leetcode 148. 排序链表(归并排序)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 148. 排序链表(归并排序)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給你鏈表的頭結(jié)點(diǎn) head ,請將其按 升序 排列并返回 排序后的鏈表 。
進(jìn)階:
你可以在 O(n log n) 時(shí)間復(fù)雜度和常數(shù)級空間復(fù)雜度下,對鏈表進(jì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)//雙指針找中點(diǎn){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) {//將兩個(gè)鏈表合并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;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 148. 排序链表(归并排序)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到鱼咬自己的手什么预兆
- 下一篇: leetcode 242. 有效的字母异