Leetcode-Python3-合併兩個有序鏈表


```python
# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):#初始化一個結點
        self.val = x
        self.next = None

def pri_node(p):#打印結點以供測試
    while p:
        print(p.val)
        p=p.next

class Solution:


    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        p=ListNode(0)
        l3=p
        if not l1:
            return l2
        if not l2:
            return l1
        while l1 and l2:
            if l1.val>l2.val:
                l3.next=ListNode(l2.val)
                l3=l3.next
                l2=l2.next
            else:
                l3.next=ListNode(l1.val)
                l3=l3.next
                l1=l1.next
        if l1:
            while(l1):
                l3.next=ListNode(l1.val)
                l3=l3.next
                l1=l1.next
        if l2:
            while(l2):
                l3.next=ListNode(l2.val)
                l3=l3.next
                l2=l2.next
        return p.next


if __name__=="__main__":
    #124 134
    l1=ListNode(1)
    p=l1
    p.next=ListNode(2)
    p=p.next
    p.next=ListNode(4)
    p=p.next
    l2=ListNode(1)
    q=l2
    q.next=ListNode(3)
    q=q.next
    q.next=ListNode(4)
    q=q.next
    S=Solution()
    r=S.mergeTwoLists(l1,l2)
    pri_node(r)

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