[LeetCode] sort-list

来源:互联网 发布:伊朗 知乎 编辑:程序博客网 时间:2024/06/06 14:15

sort-list
题目描述

Sort a linked list in O(n log n) time using constant space complexity.

链表排序。。要求用O(n log n)的复杂度。好像只有归并排序比较适合

把链表分成两部分的时候用快慢指针:当快指针遍历结束后,慢指针刚到中间。

/** * Definition for singly-linked list. * class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode sortList(ListNode head) {      if(head==null||head.next==null) return head;        ListNode slow = head;        ListNode fast = head;        while(fast.next!=null&&fast.next.next!=null){            slow = slow.next;            fast = fast.next.next;        }        fast = slow.next;        slow.next = null;        ListNode l = sortList(head);        ListNode r = sortList(fast);        return merge(l, r);    }    public  ListNode merge(ListNode l,ListNode r){        if(l==null) return r;        if(r==null) return l;        ListNode head1 = new ListNode(0);        ListNode temp = head1;        while(l!=null&&r!=null){            if(l.val<r.val){                temp.next = l;                l = l.next;            }else{                temp.next = r;                r = r.next;            }            temp = temp.next;            if(l!=null){                temp.next = l;             }            if(r!=null){                temp.next = r;            }        }        return head1.next;    }}
0 0