173. Insertion Sort List
Description:
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.
Code
1.
超时报错
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def switchNode(self, n1n, n2n):
tmp1 = n1n.next
tmp2 = n2n.next
tmp = tmp1.next
tmp1.next = tmp2.next
tmp2.next = tmp
n1n.next = tmp2
n2n.next = tmp1
def insertionSortList(self, head):
# write your code here
zero = ListNode(0)
zero.next = head
tmp1 = head
while tmp1.next:
if tmp1.val > tmp1.next.val:
tmp2 = zero.next
while tmp2.next.val < tmp1.next.val:
tmp2 = tmp2.next
self.switchNode(tmp2, tmp1)
else:
tmp1 = tmp1.next
return zero.next
2.
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of linked list.
@return: The head of linked list.
"""
def insertNode(self, n1n, n2n):
tmp = n2n.next
n2n.next = tmp.next
tmp.next = n1n.next
n1n.next = tmp
def insertionSortList(self, head):
# write your code here
zero = ListNode(0)
zero.next = head
tmp1 = head
while tmp1.next:
if tmp1.val > tmp1.next.val:
tmp2 = zero
while tmp2.next.val <= tmp1.next.val:
tmp2 = tmp2.next
self.insertNode(tmp2, tmp1)
else:
tmp1 = tmp1.next
return zero.next