剑指offer-删除链表中重复的结点(python)

这题一直卡着,之前做过删除重复的保留一个,这样就简单很多,但是这次一个也不要留,一下子卡住了,不知道怎么处理。搜集了大家的答案,看了很多用递归的,但是感觉还是想不出来,所以还是选择不用递归去写。

解释一下:
需要设置三个指针,一个是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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值