[LeetCode] 148. Sort List 链表排序

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

解法:归并排序。由于有时间和空间复杂度的要求。把链表从中间分开,递归下去,都最后两个node时开始合并,返回上一层继续合并,直到结束。找中间点的方法可以用快慢指针,快指针走2步,慢指针走1步。也可以求出链表长度,再分开链表。

Java:

public class Solution {

  public ListNode sortList(ListNode head) {
    if (head == null || head.next == null)
      return head;

    // step 1. cut the list to two halves
    ListNode prev = null, slow = head, fast = head;

    while (fast != null && fast.next != null) {
      prev = slow;
      slow = slow.next;
      fast = fast.next.next;
    }

    prev.next = null;

    // step 2. sort each half
    ListNode l1 = sortList(head);
    ListNode l2 = sortList(slow);

    // step 3. merge l1 and l2
    return merge(l1, l2);
  }

  ListNode merge(ListNode l1, ListNode l2) {
    ListNode l = new ListNode(0), p = l;

    while (l1 != null && l2 != null) {
      if (l1.val < l2.val) {
        p.next = l1;
        l1 = l1.next;
      } else {
        p.next = l2;
        l2 = l2.next;
      }
      p = p.next;
    }

    if (l1 != null)
      p.next = l1;

    if (l2 != null)
      p.next = l2;

    return l.next;
  }

}

Python:

class Solution(object):
    def merge(self, h1, h2):
        dummy = tail = ListNode(None)
        while h1 and h2:
            if h1.val < h2.val:
                tail.next, tail, h1 = h1, h1, h1.next
            else:
                tail.next, tail, h2 = h2, h2, h2.next

        tail.next = h1 or h2
        return dummy.next

    def sortList(self, head):
        if not head or not head.next:
            return head

        pre, slow, fast = None, head, head
        while fast and fast.next:
            pre, slow, fast = slow, slow.next, fast.next.next
        pre.next = None

        return self.merge(*map(self.sortList, (head, slow))) 

C++:

class Solution {
public:
	ListNode *sortList(ListNode *head) {
		if(!head || !(head->next)) return head;

		//get the linked list‘s length
		ListNode* cur = head;
		int length = 0;
		while(cur){
			length++;
			cur = cur->next;
		}

		ListNode dummy(0);
		dummy.next = head;
		ListNode *left, *right, *tail;
		for(int step = 1; step < length; step <<= 1){
			cur = dummy.next;
			tail = &dummy;
			while(cur){
				left = cur;
				right = split(left, step);
				cur = split(right,step);
				tail = merge(left, right, tail);
			}
		}
		return dummy.next;
	}
private:
	/**
	 * Divide the linked list into two lists,
     * while the first list contains first n ndoes
	 * return the second list‘s head
	 */
	ListNode* split(ListNode *head, int n){
		//if(!head) return NULL;
		for(int i = 1; head && i < n; i++) head = head->next;

		if(!head) return NULL;
		ListNode *second = head->next;
		head->next = NULL;
		return second;
	}
	/**
	  * merge the two sorted linked list l1 and l2,
	  * then append the merged sorted linked list to the node head
	  * return the tail of the merged sorted linked list
	 */
	ListNode* merge(ListNode* l1, ListNode* l2, ListNode* head){
		ListNode *cur = head;
		while(l1 && l2){
			if(l1->val > l2->val){
				cur->next = l2;
				cur = l2;
				l2 = l2->next;
			}
			else{
				cur->next = l1;
				cur = l1;
				l1 = l1->next;
			}
		}
		cur->next = (l1 ? l1 : l2);
		while(cur->next) cur = cur->next;
		return cur;
	}
};

  

  

原文地址:https://www.cnblogs.com/lightwindy/p/9609026.html

时间: 2024-11-08 22:46:05

[LeetCode] 148. Sort List 链表排序的相关文章

[LeetCode]148. Sort List链表归并排序

要求时间复杂度O(nlogn),空间复杂度O(1),采用归并排序 传统的归并排序空间复杂度是O(n),原因是要用一个数组表示合并后的数组,但是这里用链表表示有序链表合并后的链表,由于链表空间复杂度是O(1),所以可以. 链表问题经常出现TLE问题或者MLE问题,这时候要检查链表拼接过程或者循环过程,看有没有死循环 public ListNode sortList(ListNode head) { if (head==null||head.next==null) return head; //利用

Leetcode 148. Sort List 归并排序 in Java

148. Sort List Total Accepted: 81218 Total Submissions: 309907 Difficulty: Medium Sort a linked list in O(n log n) time using constant space complexity. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; *

[Lintcode]98. Sort List/[Leetcode]148. Sort List

98. Sort List/148. Sort List 本题难度: Medium Topic: Linked List Description Sort a linked list in O(n log n) time using constant space complexity. Example Example 1: Input: 1->3->2->null Output: 1->2->3->null Example 2: Input: 1->7->2

[LeetCode] Sort List 链表排序

Sort a linked list in O(n log n) time using constant space complexity. 常见排序方法有很多,插入排序,选择排序,堆排序,快速排序,冒泡排序,归并排序,桶排序等等..它们的时间复杂度不尽相同,而这里题目限定了时间必须为O(nlgn),符合要求只有快速排序,归并排序,堆排序,而根据单链表的特点,最适于用归并排序.代码如下: /** * Definition for singly-linked list. * struct List

[LeetCode] 148. Sort List 解题思路

Sort a linked list in O(n log n) time using constant space complexity. 问题:对一个单列表排序,要求时间复杂度为 O(n*logn),额外空间为 O(1). O(n*logn) 时间排序算法,无法是 quick sort, merge sort, head sort.quick sort 需要灵活访问前后元素,适合于数组,merge sort 只需要从左到右扫过去即可,可用于列表结构. 当列表元素个数大于2时,将列表拆分为左右

148 Sort List 链表上的归并排序和快速排序

在使用O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序. 详见:https://leetcode.com/problems/sort-list/description/ 方法一:归并排序 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class

[LintCode] Sort List 链表排序

Sort a linked list in O(n log n) time using constant space complexity. Have you met this question in a real interview? Yes Example Given 1->3->2->null, sort it to 1->2->3->null. Challenge Solve it by merge sort & quick sort separatel

LeetCode 75. Sort Colors(排序颜色)

Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and bl

leetcode 148. Sort List ----- java

Sort a linked list in O(n log n) time using constant space complexity. 排序,要求是O(nlog(n))的时间复杂度和常数的空间复杂度,那么就使用归并就可以了. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ p