剑指offer 之删除链表中重复的节点

"""
    在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,
    重复的结点不保留,返回链表头指针。
    例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
    思路:
        1.先设置新的非数字类型的头结点
        2.通过循环求出相同结点的值,并赋值给变量
        3.再次循环链表,如结点的值和刚才赋值变量的值相同,则跳过该节点
        4.最后输出新头结点的下一个结点,即原链表的头结点

"""


class Node:
    def __init__(self, value):
        self.value = value
        self.next = None


class Solution:

    def deleteDuplication(self, pHead):
        new_head = Node('a')
        new_head.next = pHead
        pre, cur = None, new_head
        while cur:
            pre = cur
            cur = cur.next
            while cur and cur.next and cur.value == cur.next.value:
                t = cur.value
                while cur and t == cur.value:
                    cur = cur.next
                pre.next = cur

        return new_head.next


if __name__ == '__main__':
    s = Solution()
    n1 = Node(1)
    n1.next = Node(2)
    n1.next.next = Node(3)
    n1.next.next.next = Node(3)
    n1.next.next.next.next = Node(4)
    n1.next.next.next.next.next = Node(4)
    n1.next.next.next.next.next.next = Node(5)
    result = s.deleteDuplication(n1)
    while result:
        print(result.value)
        result = result.next

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值