设为首页 加入收藏

TOP

LeetCode-Insertion Sort List (Python)
2015-07-24 05:50:47 来源: 作者: 【 】 浏览:4
Tags:LeetCode-Insertion Sort List Python

【问题】

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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇poj2288(Islands and Bridges) 状.. 下一篇POJ 3628 Bookshelf 2 题解

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: