问题概述
给定一个已排序的链表的头 head,删除所有重复的元素,使每个元素只出现一次。返回同样已排序的链表。
解法 1:迭代(推荐)
工作原理
遍历链表,通过更新 next 指针跳过重复节点来删除重复元素:
python
class Solution:
def deleteDuplicates(self, head):
if not head:
return head
current = head
while current and current.next:
if current.val == current.next.val:
# 跳过重复节点
current.next = current.next.next
else:
# 移动到下一个节点
current = current.next
return head
复杂度分析
- 时间复杂度: O(n) - 单次遍历链表
- 空间复杂度: O(1) - 只使用常数额外空间
何时使用
- 推荐 - 简单高效
- 链表操作的标准方法
- 处理所有边界情况,包括空链表
对比
| 方法 | 时间 | 空间 | 最佳适用 |
|---|---|---|---|
| 迭代 | O(n) | O(1) | 大多数情况,最优解 |
总结
迭代方法通过一次遍历并跳过重复节点,高效地从已排序链表中删除重复元素。由于链表已排序,重复元素总是相邻的,这使得解决方案非常直接。