[Leetcode] Sort list

Source: Internet
Author: User

Sort list

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

 

Algorithm idea:

The time complexity is O (nlogn) sorting algorithms, such as fast sorting, Merge Sorting, and heap sorting. The fast sorting needs to be traversed forward. Therefore, it is not suitable for single-chain tables, and heap sorting is acceptable, however, the space of O (n) is required, so the best answer to this question should be the merge order.

It is consistent with the merge sort idea of array.

The Code is as follows:

 1 public class Solution { 2  public ListNode sortList(ListNode head) { 3         if(head == null || head.next == null) return head; 4         ListNode hhead = new ListNode(0); 5         hhead.next = head; 6         ListNode fast = hhead; 7         ListNode slow = hhead; 8         while(fast != null && fast.next != null){ 9             fast = fast.next.next;10             slow = slow.next;11         }12         ListNode right = slow.next;13         slow.next = null;14         ListNode left = sortList(head);15         right = sortList(right);16         return merge(left, right);17     }18     private ListNode merge(ListNode l1,ListNode l2){19         ListNode hhead = new ListNode(0);20         hhead.next = l1;21         ListNode p = hhead;22         while(p.next != null){23             if(p.next.val > l2.val){24                 ListNode tem = l2;25                 l2 = l2.next;26                 tem.next = p.next;27                 p.next = tem;28             }else29                 p = p.next;30                 if(l2 == null) return hhead.next;31             }32         p.next = l2;33         return hhead.next;34         }35 }

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.