Python 删除排序链表中的重复元素

给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。

示例 1:

输入:head = [1,1,2]
输出:[1,2]

示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

算法逻辑

定义一个指针并且从头节点开始遍历链表。

如果当前节点的数据与下一个节点的数据相同,则将当前节点的next指针指向下下个节点,从而跳过重复的节点。

如果当前节点的数据与下一个节点的数据不同,则继续遍历链表。

    def check(self):
        current = self.head
        if self.head == None:
            return
        while current and current.next:
            if current.data == current.next.data:
                current.next = current.next.next
            else:
                current = current.next

完整代码


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

class linked_list:
    def __init__(self):
        self.head = None
    def insert(self,data):
        new_node = Node(data)
        if self.head == None:
            self.head = new_node
        else:
            current = self.head
            while current.next:
                current = current.next
            current.next = new_node

    def check(self):
        current = self.head
        if self.head == None:
            return
        while current and current.next:
            if current.data == current.next.data:
                current.next = current.next.next
            else:
                current = current.next
    def display(self):
        if self.head == None:
            return
        else:
            current = self.head
            while current.next:
                print(current.data,end = "->")
                current = current.next
            print(current.data,"\n")

list_0 = linked_list()
list_0.insert(1)
list_0.insert(1)
list_0.insert(2)
list_0.insert(2)
list_0.insert(3)
list_0.insert(3)
list_0.check()
list_0.display()

代码的时间复杂度为O(n)但此代码仅限于已排序的链表

在评论群评论留下自己的观点,博主下期会更新单链表的遍历插入输出指定位置元素输出指定元素的位置输出返回链表长度以及链表的排序等操作,代码实现起来也不会很难,博主会以最通俗易懂的方式实现上述功能,不必担心看不懂,实际上你们会做的比我更好。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值