思路:
遍历结点,遇到相同的跳过一个结点(删除)
def deleteDuplicates(self, head):
if head == None:
return head
cur = head
while cur.next != None:
first = cur.val
ccur = cur.next
second = ccur.val
# 删除重复结点,保留其中一个
if second == first:
ccur = ccur.next
cur.next = ccur
else:
cur = ccur
return head
删除且不保留其中一个重复元素
题目是不保留重复元素思路:
双指针:快慢指针,用快指针找到相同的或者不同的值,并用flag标记,找到不同的值后用慢指针指向。
def deleteDuplicates(self, head: ListNode) -> ListNode:
dummy = ListNode(0)
slow = dummy
fast = head
while fast != None:
# 是否快进的标志
flag = False
while fast.next !=None and fast.val == fast.next.val:
flag = True
fast = fast.next
if not flag:
slow.next = fast
slow = slow.next
fast = fast.next
slow.next = None
return dummy.next
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)