劍指 Offer 25:合併兩個排序的鏈表

輸入兩個遞增排序的鏈表,合併這兩個鏈表並使新鏈表中的節點仍然是遞增排序的。

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
// 時間度底的寫法 優雅
class LinkNode():
    def __init__(self, value, next = None):
        self.value = value
        self.next = next


class Solution():
    def mergeTwoLists(self, l1: LinkNode, l2: LinkNode) -> LinkNode:
        if l1 is None: return None
        if l2 is None: return None

        cur = dum = LinkNode(0)
        while l1 and l2:
            if l1.value < l2.value:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        cur.next = l1 if l1 else l2
        return dum.next



# 生成A鏈表
headA1 = LinkNode(4, None)
headA2 = LinkNode(2, headA1)
headA3 = LinkNode(1, headA2)

# 生成B鏈表
headB1 = LinkNode(4, None)
headB2 = LinkNode(3, headB1)
headB3 = LinkNode(1, headB2)

solu = Solution()
value = solu.mergeTwoLists(headA3, headB3)
print(value)
// 較差寫法
class LinkNode():
    def __init__(self, value, next = None):
        self.value = value
        self.next = next


class Solution():
    def mergeTwoLists(self, headA:LinkNode, headB:LinkNode) -> LinkNode:
        if headA is None: return None
        if headB is None: return None

        listA, listB = [], []
        while headA:
            listA.append(headA)
            headA = headA.next

        while headB:
            listB.append(headB)
            headB = headB.next

        newNode = None
        while listA or listB:
            nodeA = listA.pop()
            nodeB = listB.pop()

            curNode = None
            if nodeA is None:
                curNode = LinkNode(nodeA.value)
                curNode.next = newNode
                newNode = curNode
            elif nodeB is None:
                curNode = LinkNode(nodeB.value)
                curNode.next = newNode
                newNode = curNode
            else:
                if nodeA.value <= nodeB.value:
                    nodeA.next = nodeB
                    nodeB.next = newNode
                    newNode = nodeA
                else:
                    nodeB.next = nodeA
                    nodeA.next = newNode
                    newNode = nodeB

        return newNode



# 生成A鏈表
headA1 = LinkNode(4, None)
headA2 = LinkNode(2, headA1)
headA3 = LinkNode(1, headA2)

# 生成B鏈表
headB1 = LinkNode(4, None)
headB2 = LinkNode(3, headB1)
headB3 = LinkNode(1, headB2)

solu = Solution()
value = solu.mergeTwoLists(headA3, headB3)
print(value)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章