Sort List

来源:互联网 发布:网络合同 编辑:程序博客网 时间:2024/05/16 14:37
Sort a linked list in O(n log n) time using constant space complexity.

/** * 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 fast=head;       ListNode slow=head;       while(fast.next!=null && fast.next.next!=null){           fast=fast.next.next;           slow=slow.next;       }       fast=slow;       slow=slow.next;       fast.next=null;              ListNode l1=sortList(head);       ListNode l2=sortList(slow);       return mergeList(l1,l2);    }    public ListNode mergeList(ListNode l1,ListNode l2){        ListNode tmp=new ListNode(-1);        for(ListNode node=tmp; l1!=null || l2!=null ;node=node.next){            int val1=(l1==null)?Integer.MAX_VALUE:l1.val;            int val2=(l2==null)?Integer.MAX_VALUE:l2.val;            if(val1<=val2){                node.next=l1;                l1=l1.next;            }            else{                node.next=l2;                l2=l2.next;            }        }        return tmp.next;    }}
思路:用归并对链表进行排序

0 0
原创粉丝点击