码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode] Insertion Sort List(python)

时间:2014-07-06 11:52:20      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:algorithm   面试题   python   leetcode   插入排序   

简单的插入排序,总是超时,暂且放在这记录一下。

class Solution:
    # @param head, a ListNode
    # @return a ListNode
    def insertionSortList(self, head):

		if head == None or head.next == None:
			return head
		psuhead = ListNode(-1)
		while head:
			tail = psuhead
			headnext = head.next
			while tail.next and tail.next.val < head.val:
				tail = tail.next
			head.next = tail.next
			tail.next = head
			head = headnext
		return psuhead.next

Last executed input: {0,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,2
c++AC的

ListNode *insertionSortList(ListNode *head) {
	if(head == NULL || head->next == NULL)
		return head;
	//排序涉及到头结点的变化,为了方便,我们定义一个额外的伪头结点
	ListNode *psuHead = new ListNode(-1);
	while(head){
		ListNode *pre = psuHead;
		ListNode *tail = psuHead->next;
		while(tail && tail->val < head->val){
			pre = tail;
			tail = tail->next;
		}
		ListNode *nextHead = head->next;
		head->next = pre->next;
		pre->next = head;
		head = nextHead;
	}

	head = psuHead->next;
	delete (psuHead);
	return head;
}


[leetcode] Insertion Sort List(python),布布扣,bubuko.com

[leetcode] Insertion Sort List(python)

标签:algorithm   面试题   python   leetcode   插入排序   

原文地址:http://blog.csdn.net/shiquxinkong/article/details/37053453

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!