在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:
设置三个指针。一个pre用于构建返回链表,一个p用于前移,一个nex用于比较当前值是否与p值相等。
代码:
class Solution:
def deleteDuplication(self, pHead):
# write code here
if pHead==None or pHead.next==None:
return pHead
newhead=ListNode(-1)
newhead.next=pHead
pre=newhead
p=pHead
nex=None
while p!=None and p.next!=None:
nex=p.next
if p.val==nex.val:
while nex!=None and nex.val==p.val:
nex=nex.next
pre.next=nex
p=nex
else:
pre=p
p=p.next
return newhead.next
分析:
只需要扫描一遍即可。