[leetcode] Insertion Sort List(python)

簡單的插入排序,總是超時,暫且放在這記錄一下。

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;
}


發佈了243 篇原創文章 · 獲贊 4 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章