輸入兩個遞增排序的鏈表,合併這兩個鏈表並使新鏈表中的節點仍然是遞增排序的。
示例1:
輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4
限制:
0 <= 鏈表長度 <= 1000
注意:本題與主站 21 題相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
思路1:遍歷
構建一個頭節點,記錄起點,然後遍歷兩個鏈表,將小的插入新鏈表,依次遍歷,直到兩者爲空。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = ListNode()
first = head
while l1 != None or l2 != None:
if l1 and l2:
if l1.val < l2.val:
head.next = l1
head = l1
l1 = l1.next
else:
head.next = l2
head = l2
l2 = l2.next
elif l1:
head.next = l1
head = l1
l1 = l1.next
break
else:
head.next = l2
head = l2
l2 = l2.next
break
return first.next