[leetcode] Insertion Sort List

Sort a linked list using insertion sort.

思路:思路上和insertion sort一致,需要注意的是,需要判斷前一個元素是否比當前元素大,如果大的話,則需要insertion, 從head開始遍歷直至找到插入的位置,注意邊界條件

# 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
        newhead = head
        pre = newhead
        node = newhead.next
        while node != None:
            if node.val < pre.val:
                pre.next = node.next
                if node.val < newhead.val:
                    node.next = newhead
                    newhead = node
                else:
                    phead = newhead
                    while phead.next.val < node.val:
                        phead = phead.next
                        continue
                    node.next = phead.next
                    phead.next = node
                node = pre.next
            else:
                node = node.next
                pre = pre.next
        return newhead
                        
                    
            


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