剑指offer:018-2删除有序链表中所有重复的点

本文介绍了一种使用Python实现链表的方法,并详细讲解了如何在排序链表中删除重复节点的具体算法。通过定义Node和LinkList类,创建链表结构,并提供遍历链表和删除重复节点的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 在一个排序链表中,删除重复的点
# 利用python实现链表的
class Node:
    def __init__(self, data, next):
        self.data = data
        self.next = next


# 包含头结点的链表
class LinkList:
    def __init__(self, input):
        self.headNode = Node(None, None)
        if input is None:
            pass
        else:
            work = self.headNode
            for i in input:
                newnode = Node(i, None)
                work.next = newnode
                work = work.next

    def travelLinkList(self):
        work = self.headNode
        while work.next is not None:
            print(work.next.data)
            work = work.next


#
def delete_duplicate_node(head_node):
    # 定义3个指针,分别是pre_p, cur_p, next_p
    # 指针初始化
    if head_node is None:
        return
    else:
        pre_p = head_node
        if pre_p.next is not None:
            cur_p = pre_p.next
        else:
            return
        if cur_p.next is not None:
            next_p = cur_p.next
        else:
            return
        
        # 开始删除
        
        while next_p is not None:
            if cur_p.data != next_p.data:  # 如果cur_p和next_p指向的值不想等,那么三个指针整体向后移动一位
                pre_p = cur_p
                cur_p = next_p
                next_p = next_p.next
            else:  # 发现重复的值,则将cur_p指针向后移动到不重复的节点
                while cur_p and cur_p.data == next_p.data:
                    cur_p = cur_p.next
                # pre_p 与 cur_p 连接
                pre_p.next = cur_p
                if cur_p is None:  # 如果cur_p为None,说明pre_p之后的所有节点都为None
                    next_p = None  # next_p置为None,跳出while
                else:
                    next_p = cur_p.next # 如果cur_p非None,next_p指向cur_p的下一个节点,继续while
    return head_node


if __name__ == '__main__':
    # 测试用例
    # array = [1, 2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 6, 6, 6]
    # array = [6, 6, 6, 6, 1]
    array = [1,2,3,4,5,7]
    link_list = LinkList(array)
    head_node = delete_duplicate_node(link_list.headNode)
    link_list.travelLinkList()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值