83删除排序链表中的重复元素
1.双指针,注意边界,链表为[]不存在head.next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None:
return head
s,f=head,head.next
while f:
if s.val!=f.val:
s=s.next
f=f.next
else:
f=f.next
s.next=f
return head
2.递归
递归讲解
①停止条件:只剩一个元素或空,head,head.next==None
②等价关系:deleteDuplicates(head)=deleteDuplicates(head.next)+检查head与head.next是否相等
class Solution(object):
def deleteDuplicates(self, head):
if head==None or head.next==None:
return head
###每一次递归指向已经去重的序列###
head.next=self.deleteDuplicates(head.next)
if head.val==head.next.val:
head=head.next
'''另一种写法:
tmp = self.deleteDuplicates(head.next)
#if not tmp:
# return head
head.next = tmp.next if head.val == tmp.val else tmp
'''
return head
删除链表中的重复元素II
cur指针从哑节点开始
判断cur.next与cur.next.next是否同值
储存该值,并不断向后判断值取到不同值时停止
若不同则更新cur,cur=cur.next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None:return head
dummy=ListNode(next=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