两个有序链表合并(新表不含重复元素)
时间: 2023-09-13 14:04:52 浏览: 112
两个有序链表的合并
好的,这是一个经典的数据结构问题。我们可以定义一个新的链表,遍历两个有序链表,将较小的元素加入新链表中,直至任一链表为空。如果有重复元素,只加入一次即可。以下是一个示例代码:
```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()
curr = dummy
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
elif l1.val > l2.val:
curr.next = l2
l2 = l2.next
else:
curr.next = l1
l1 = l1.next
l2 = l2.next
curr = curr.next
if l1:
curr.next = l1
if l2:
curr.next = l2
return dummy.next
```
希望这能够帮助你解决问题!
阅读全文