-
Notifications
You must be signed in to change notification settings - Fork 319
/
Copy path148_SortList.py
84 lines (71 loc) · 2.16 KB
/
148_SortList.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: [email protected]
# @Last Modified time: 2016-09-06 20:03:53
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
# Merge Sort
class Solution(object):
def sortList(self, head):
if not head or not head.next:
return head
# Get the two half parts.
pre_slow = None
slow = fast = head
while fast and fast.next:
pre_slow = slow
slow = slow.next
fast = fast.next.next
pre_slow.next = None # Cut the linked list to two parts.
left_list = self.sortList(head)
right_list = self.sortList(slow)
return self.merge(left_list, right_list)
# Operator merge.
def merge(self, left_list, right_list):
pre_head = dummy = ListNode(None)
while left_list and right_list:
if left_list.val < right_list.val:
dummy.next = left_list
left_list = left_list.next
else:
dummy.next = right_list
right_list = right_list.next
dummy = dummy.next
dummy.next = left_list or right_list
return pre_head.next
# Quick sort: Time Limit Exceeded
class Solution_2(object):
def partition(self, begin, end):
if not begin or begin.next == end:
return begin
pivot = begin.val
keep, pos = begin, begin
scan = begin.next
while scan != end:
if scan.val <= pivot:
pos = pos.next
if scan != pos:
scan.val, pos.val = pos.val, scan.val
scan = scan.next
pos.val, keep.val = keep.val, pos.val
return pos
def quick_sort(self, begin, end):
if begin == end or begin.next == end:
return begin
pos = self.partition(begin, end)
head = self.quick_sort(begin, pos)
self.quick_sort(pos.next, end)
return head
def sortList(self, head):
return self.quick_sort(head, None)
"""
[]
[1]
[1,2]
[5,1,2]
[5,1,2,3]
[5,1,2,3,6,7,8,9,12,2]
"""