【Leetcode】Python 代码本地构造二叉树、链表
生活随笔
收集整理的這篇文章主要介紹了
【Leetcode】Python 代码本地构造二叉树、链表
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
生成二叉樹
生成列表
#定義節點 class ListNode():def __init__(self, x):self.val = xself.next = None #將傳入的數組轉化為鏈表 def create_linked_list(arr):head = ListNode(arr[0])cur = headfor i in range(1, len(arr)):cur.next = ListNode(arr[i])cur = cur.nextreturn head #傳入鏈表頭節點,以數組形式返回 def print_linked_list(head):cur = headres = []while cur:res.append(cur.val)cur = cur.nextreturn res class Solution():def mergeTwoLists(self, l1, l2):pre = ListNode(0)head = prewhile l1 and l2:if l1.val >= l2.val:pre.next = l2l2 = l2.nextelse:pre.next = l1l1 = l1.nextpre = pre.nextpre.next = l1 if l1 else l2return head.next if __name__ == "__main__":head1 = create_linked_list([1, 2, 4])head2 = create_linked_list([1, 3, 4])solution = Solution()sorted_lists = solution.mergeTwoLists(head1, head2)print(print_linked_list(sorted_lists)) #輸出:[1, 1, 2, 3, 4, 4]注:放到本地可以直接跑哦~
猜你喜歡:👇🏻
?【Leetcode】創建鏈表
?【Leetcode】創建二叉樹
?【Leetcode】大神總結的鏈表常見面試問題
總結
以上是生活随笔為你收集整理的【Leetcode】Python 代码本地构造二叉树、链表的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: enc易能变频_ENC易能变频器故障灯亮
- 下一篇: insert自动跳过存在数据_轻松入门m