7-6 数据结构实验之链表七:单链表中重复元素的删除 (20 分)
时间: 2023-05-02 07:01:52 浏览: 147
这里给出单链表中删除重复元素的实现代码:
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteDuplicates(head: ListNode) -> ListNode:
if not head:
return head
dummy = ListNode(-1)
dummy.next = head
pre, curr = dummy, head
while curr:
if curr.next and curr.next.val == curr.val:
# 如果当前节点的下一个节点与当前节点值相等,则一直往后遍历,直到不相等
while curr.next and curr.next.val == curr.val:
curr = curr.next
curr = curr.next
pre.next = curr
else:
pre = pre.next
curr = curr.next
return dummy.next
```
该算法的时间复杂度为 $O(n)$,空间复杂度为 $O(1)$。
阅读全文