"Leetcode" sort list single-linked list merge sorting

Source: Internet
Author: User

Title: Sort A linked list in O (n log n) time using constant space complexity.

Train of thought: Require time complexity O (NLOGN)

Knowledge Points: Merge sort, link list find Midpoint method

Disadvantages of existence: the boundary condition is more consideration!!!

/** * Leetcode Sort list Sort a linked list in O (n log n) time using constant space complexity. * Title: Sorting a single linked list, time complexity requires O (NLOGN) * Ideas: 1 time complexity is O (nlog n) sorting algorithm has: merge sort, fast row (expected), heap sort * 2, single-linked list sorting with merge sort, double-linked list sorting with fast row * Definition for singly-linked list.      * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; *     } *} */package javatrain;class ListNode {int val;     ListNode Next;         ListNode (int x) {val = x;     next = null; }}public class Train4 {public ListNode sortlist (ListNode head) {if (head = = NULL | | head.next = = NULL) return head; ListNode fast = head; ListNode slow = Head;while (Fast.next.next! = NULL && Slow.next! = null) {fast = fast.next.next;//makes a point to the middle after traversing the list One point to the end, that is to find the list midpoint slow = Slow.next;} ListNode List2 = Slow.next;slow.next = Null;head = Sortlist (head); list2 = Sortlist (list2); return merge (HEAD,LIST2);} private static ListNode merge (ListNode List1,listnode list2) {if (List1 = = null) return List2; if (list2 = = null) return list1; ListNode head = new ListNode (0); ListNode last = head; while (List1.next = null && list2.next! = null) {if (List1.val <= list2.val) {last.next = List1;list1 = List1.next ;} Else{last.next = List2;list2 = List2.next;} last = Last.next;} if (list1! = null) Last.next = List1;else if (list2! = null) Last.next = List2;return Head.next;}}


"Leetcode" sort list single-linked list merge sorting

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.