148. Sort List, 148 sortlist

Source: Internet
Author: User

148. Sort List, 148 sortlist

Sort a linked list inO(NLogN) Time using constant space complexity.

The Code is as follows:

 1 /** 2  * Definition for singly-linked list. 3  * public class ListNode { 4  *     int val; 5  *     ListNode next; 6  *     ListNode(int x) { val = x; } 7  * } 8  */ 9 public class Solution {10     public ListNode sortList(ListNode head) {11         if(head==null||head.next==null)12         return head;13         14         ListNode p=head;15         int count=0;16         17         while(p!=null)18         {19             count++;20             p=p.next;21         }22         int[]a=new int[count];23         int c=count;24         p=head;25        for(int i=0;i<count;i++)26        {27            if(p!=null)28            a[i]=p.val;29            p=p.next;30        }31        p=head;32        33         Arrays.sort(a);34         for(int i=0;i<c;i++)35         {36             p.val=a[i];37             p=p.next;38         }39         return head;40     }41 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.