剑指offer_链表_删除链表中重复的结点

链表_删除链表中重复的结点

在这里插入图片描述
思路:因为重复的节点都要删除,因此需要标记重复开始前的上一个节点,又因为头结点有可能是重复的节点,为了操作方便,我们可以再链表前面设置一个空节点作为头结点,因此需要设置3个指针,第一个head指向头结点。第二个p用来标记重复节点的前面一个节点,第三个cur用来寻找重复的节点,一旦找到p就不移动了,cur继续往后寻找直到不是重复的节点。
参考答案

# -*- 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(-1)
        p = head
        p.next = pHead
        cur = pHead
        while cur and cur.next:
            if cur.val != cur.next.val:
                p = p.next
                cur = cur.next
            else:
                val = cur.val
                while cur and cur.val == val:
                    cur = cur.next
                p.next = cur
        return head.next

精简代码:

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @return ListNode类
#
class Solution:
    def deleteDuplicates(self , head: ListNode) -> ListNode:
        # write code here
        newhead = ListNode(-1)
        phead = newhead
        phead.next = head
        while head and head.next:
            if head.val != head.next.val:
                phead = phead.next
                head = head.next
            else:
                tmp = head.val
                while head and head.val == tmp:
                    head = head.next
                phead.next = head
        return newhead.next

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值