这题一直卡着,之前做过删除重复的保留一个,这样就简单很多,但是这次一个也不要留,一下子卡住了,不知道怎么处理。搜集了大家的答案,看了很多用递归的,但是感觉还是想不出来,所以还是选择不用递归去写。
解释一下:
需要设置三个指针,一个是cur,遇到重复的就一直往下走,head重新设置一个头结点,pre=head,pre遇到不重复的在连接,最后返回head.next
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
head=ListNode(0)
head.next=pHead
cur=pHead
pre=cur
while cur and cur.next:
if cur.val!=cur.next.val:
pre=cur
cur=cur.next
else:
val=cur.val
while cur and cur.val==val:
cur=cur.next
pre.next=cur
return head.next