将两个线性链表合并成一个线性链表并返回
时间: 2023-05-16 22:05:34 浏览: 108
实现对两个线形链表的合并,并输出其结果
以下是将两个线性链表合并成一个线性链表并返回的代码示例:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode(0)
curr = dummy
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
if l1:
curr.next = l1
else:
curr.next = l2
return dummy.next
```
这段代码可以将两个有序的线性链表合并成一个有序的线性链表,并返回合并后的链表头节点。
阅读全文