Sort List

来源:互联网 发布:freebsd 安装python 编辑:程序博客网 时间:2024/05/29 14:05

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

思路:归并排序。每次将一个链表分成两段,递归地排序左右两个子段,再将排好序的两子段合并起来。

特别注意:java传引用,因此divide函数中不能将head1、head2重定向,即不能有head1=xx,head2=xx的情况出现,否则函数之外的head1、head2值不变。

故特别需要注意第21~25行关于head1、head2的写法。

/** * 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) {int N=0;for(ListNode p=head;p!=null;p=p.next)N++;return sortList(head,N);    }public ListNode sortList(ListNode head,int len) {if(len <= 1)            return head;ListNode head1= new ListNode(-1),head2= new ListNode(-1);        int len1=len / 2,len2=len - len1;        divide(head,len,head1,len1,head2,len2);//Pay attention to transfer the reference        head1 = sortList(head1.next,len1);        head2 = sortList(head2.next,len2);        return mergeTwoLists(head1,head2);}public void divide(ListNode head,int len,ListNode head1,        int len1,ListNode head2,int len2){        ListNode tp = head;        head1.next = head;        for(int i = 1;i <len1;i++){            tp = tp.next;        }        head2.next = tp.next;        tp.next=null;    }//mergepublic ListNode mergeTwoLists(ListNode l1, ListNode l2) {ListNode l3=new ListNode(-1); ListNode head=l3;//merge others  while(l1!=null||l2!=null){ if(l1==null){ l3.next=l2; break; }else if(l2==null){ l3.next=l1; break; }else if(l1.val<=l2.val){ l3.next=l1; l1=l1.next; }else{ l3.next=l2; l2=l2.next; } l3=l3.next; } return head.next; }}


0 0