21. 合并两个有序链表
题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
题解
定义一个头结点,一个last_node用来记录上一个节点.
之后就是比较l1.val
和l2.val
的大小,小的就赋值给last_node.next
,同时后移一位.
移到最后没有后续节点了,整个last_node
的后续就是未完的那个链表的后续.
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
if l1 == None:
return l2
if l2 == None:
return l1
head = ListNode()
last_node = ListNode()
if l1.val <= l2.val:
head = l1
last_node = l1
l1 = l1.next
else:
head = l2
last_node = l2
l2 = l2.next
while 1:
if l1 == None:
last_node.next = l2
break
if l2 == None:
last_node.next = l1
if l1.val <= l2.val:
last_node.next = l1
l1 = l1.next
else:
last_node.next = l2
l2 = l2.next
last_node = last_node.next
return head
Python学到了
今天没学到啥