两个有序链表合并(新表不含重复元素)
时间: 2023-09-13 14:04:12 浏览: 76
好的,下面是合并两个有序链表并去除重复元素的代码示例:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def mergeLists(l1: ListNode, l2: ListNode) -> ListNode:
dummy = ListNode()
current = dummy
while l1 and l2:
if l1.val < l2.val:
if not current.next or current.next.val != l1.val:
current.next = ListNode(l1.val)
current = current.next
l1 = l1.next
else:
if not current.next or current.next.val != l2.val:
current.next = ListNode(l2.val)
current = current.next
l2 = l2.next
while l1:
if not current.next or current.next.val != l1.val:
current.next = ListNode(l1.val)
current = current.next
l1 = l1.next
while l2:
if not current.next or current.next.val != l2.val:
current.next = ListNode(l2.val)
current = current.next
l2 = l2.next
return dummy.next
```
以上代码是使用 Python 语言实现的,输入两个有序链表 l1 和 l2,返回一个新的链表,该链表的元素是 l1 和 l2 中的不重复元素按照升序排列。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)