劍指 Offer 25. 合併兩個排序的連結串列_CodingPark程式設計公園
阿新 • • 發佈:2021-01-11
合併兩個排序的連結串列
問題
輸入兩個遞增排序的連結串列,合併這兩個連結串列並使新連結串列中的節點仍然是遞增排序的。
示例1:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
限制:
0 <= 連結串列長度 <= 1000
連結:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
解答
pycharm
# -*- encoding: utf-8 -*-
"""
@File : office25.py
@Contact : [email protected]
@License : (C)Copyright 2019-2020, CodingPark
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
2021/1/10 下午7:15 AG 1.0 None
"""
class ListNode:
def __init__(self, x):
self.val = x
self. next = None
o1 = ListNode(1)
o2 = o1.next = ListNode(2)
o3 = o2.next = ListNode(4) # 1 -> 2 -> 4
c1 = ListNode(1)
c2 = c1.next = ListNode(3)
c3 = c2.next = ListNode(4) # 1 -> 3 -> 4
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
fin = l3 = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
l3.next = l1
l1 = l1.next
else:
l3.next = l2
l2 = l2.next
l3 = l3.next
l3.next = l1 if l1 else l2
return fin.next
s = Solution()
fin = s.mergeTwoLists(o1, c1)
while fin:
print(fin.val)
fin = fin.next