82. 删除排序链表中的重复元素 II
链表和树的问题,一般都可以右递归和迭代俩种写法
本题链表定义
# 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: Optional[ListNode]) -> Optional[ListNode]:
#含义删除以head为头的重复节点注意是有序链表
#终止条件:head==None//head.next==None 均return head
#递归调用.
---
#先使用暴力破解
#1.找到相同元素的节点
#2.跳到相同元素的节点
#3.按照链表遍历暴力破解
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
#构造虚拟节点
dummy = ListNode(-1)
dummy.next=head
#初始化
pre = dummy
cur = head
while cur and cur.next:
if cur.val==cur.next.val:
while cur.next and cur.next.val==cur.val:
cur.next=cur.next.next
pre.next = cur.next
else:
pre = cur
cur = cur.next
return dummy.next