# 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:
index1=l1
index2=l2
head=ListNode(0)
cur=head
if index1 and not index2:
return index1
if index2 and not index1:
return index2
while(index1 and index2):
if index1.val<index2.val:
cur.next=ListNode(index1.val)
index1=index1.next
else:
cur.next=ListNode(index2.val)
index2=index2.next
cur=cur.next
if (index1):
cur.next=index1
if(index2):
cur.next=index2
return head.next
本文深入探讨了单链表的定义与实现,重点讲解了一种有效的算法——合并两个有序链表。通过创建ListNode类来定义链表节点,并实现Solution类中的mergeTwoLists方法,该方法接收两个链表作为参数,返回合并后的链表。算法首先检查两个链表是否为空,然后进行循环比较,将较小的节点插入结果链表中,直至其中一个链表遍历完毕。最后,将未遍历完的链表剩余部分直接连接到结果链表尾部。
811

被折叠的 条评论
为什么被折叠?



