程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

21. merge two ordered linked lists (Python Implementation)

編輯:Python

subject :

Merge two ascending linked lists into a new Ascending Link list and return . The new linked list is made up of all the nodes of the given two linked lists .

Example 1:

Input :l1 = [1,2,4], l2 = [1,3,4]
Output :[1,1,2,3,4,4]

Example 2:

Input :l1 = [], l2 = []
Output :[]

Example 3:

Input :l1 = [], l2 = [0]
Output :[0]

code:

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1 :
return list2
elif not list2:
return list1
res = ListNode()
ans = res
while list1 != None and list2 != None:
if list1.val <= list2.val:
ans.next = list1
list1 = list1.next
else:
ans.next = list2
list2 = list2.next
ans = ans.next
if list1 == None:
ans.next = list2
else:
ans.next = list1
return res.next

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved