您的位置:首页 > 编程语言 > Python开发

LeetCode-Insertion Sort List (Python)

2014-06-27 19:42 483 查看
【问题】

Sort a linked list using insertion sort.

【代码】

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
# @param head, a ListNode
# @return a ListNode
def insertionSortList(self, head):
if head == None or head.next == None:
return head
dummy = ListNode(0)
dummy.next = head
cur = head
while cur.next != None:
if cur.next.val < cur.val:
pre = dummy
while pre.next.val < cur.next.val:
pre = pre.next
temp = cur.next
cur.next = temp.next
temp.next = pre.next
pre.next = temp
else:
cur = cur.next
return dummy.next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python LeetCode sort