思路:我们从指针 tem 指向链表的头节点,随后开始对链表进行遍历。如果当前 tem 与 tem.next 对应的元素相同,那么我们就将 tem.next 从链表中移除;否则说明链表中已经不存在其它与 tem 对应的元素相同的节点,因此可以将 tem 指向 tem.next。当遍历完整个链表之后,我们返回链表的头节点即可。
# 遍历
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return head
tem = head # 哨兵节点
while tem.next:
if tem.val == tem.next.val:
tem.next = tem.next.next
else:
tem = tem.next
return head
方法二:递归
思路差不多,直接上代码!
# 递归
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
head.next = self.deleteDuplicates(head.next)
if head.val == head.next.val:
head.next = head.next.next
return head