82. 删除排序链表中的重复元素 II
1.题目
2.我的解决方案
没有想到哑结点这个办法
其他的思路都是和官方题解相同
到头来用了三个指针和很多的分支语句,但是因为删除head带来的干扰,始终没有通过所有的测试用例
3.官方的解决方案
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head):
if not head: # 空链表
return head
dummy = ListNode(0, head) # 由于头节点可能被删除,所以重新定义一个结点
cur = dummy
while cur.next and cur.next.next: # 当值重复的时候
if cur.next.val == cur.next.next.val:
x = cur.next.val # 存储重复值
while cur.next and cur.next.val == x:
cur.next = cur.next.next # 从前往后开始删除
else:
cur = cur.next # 在不重复的情况下,指针向前移动
return dummy.next
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)