使用快速排序算法对列表进行排序——Leetcode系列(四)

来源:互联网 发布:企业应用开发实战源码 编辑:程序博客网 时间:2024/06/05 00:53

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

My Answer:

/** * 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){            return head;        }        ListNode pivot = head;        ListNode pre = null;        ListNode first = null;        ListNode last = null;        pivot = head;        while(pivot != null){            if(pivot.val < head.val){                pre.next = pivot.next;                pivot.next = first;                first = pivot;                pivot = pre;            }else if(pivot.val > head.val){                pre.next = pivot.next;                pivot.next = last;                last = pivot;                pivot = pre;            }            pre = pivot;            pivot = pivot.next;        }                first = sortList(first);        last = sortList(last);                pivot = head;        while(pivot != null){            pre = pivot;            pivot = pivot.next;        }        pre.next = last;        if (first == null){            return head;        }        pivot = first;        while(pivot != null){            pre  = pivot;            pivot = pivot.next;        }        pre.next = head;        return first;    }}

题目来源: https://oj.leetcode.com/problems/sort-list/

0 0
原创粉丝点击