python链表操作

 python中并没有C语言里面的指针、结构体操作,所以只能通过定义类的方法来实现链表。

class node:
#定义节点
    def __init__(self,data):
        self.data=data
        #初始化next索引
        self.next=None

class linklist:
    def __init__(self):#初始化链表
        self.head=node(None)

    def isempty(self):#判断链表是否为空
        if self.head.next==None:
            return True
        else:
            return False

    def insert_head(self,data):#头插的方法插入结点
        new_node=node(data)
        if self.isempty():
            self.head.next=new_node
            return
        new_node.next=self.head.next
        self.head.next=new_node
    
    def insert_tail(self,data):#尾插的方法插入结点
        new_node=node(data)
        if self.isempty():
            self.head.next=new_node
            return
        n=self.head
        while n.next:
            n=n.next
        n.next=new_node

    def delete(self,data):#删除结点
        if self.isempty():
            print('链表为空')
            return 
        q,p=self.head,self.head.next
        while p and q:
            if p.data==data:
                q.next=p.next
                return
            p,q=p.next,q.next

    def print_all(self):#打印链表所有数据
        n=self.head.next
        while n:
            print(n.data)
            n=n.next

if __name__=='__main__':
    x=linklist()
    x.insert_tail(1)
    x.insert_tail(2)
    x.insert_tail(3)
    x.delete(2)
    x.print_all()

1、__init__方法,在linklist类里面,定义linklist的head=node(None)这是因为作为链表的头结点,head是不存放任何内容的。在整个链表中只是起到了一个索引的作用。

2、isempty方法用来判断链表是否为空,在node类的定义中,我们首先将next属性指向了None,这样的话如果head的next索引没有任何指向的话,我们认为链表中没有存放任何东西。

3、insert_head方法通过将新的节点直接放在head之后,类似于栈的操作。因为在python的内存处理机制中一旦某一部分没有任何索引指向就会被释放内存,所以在编码时,首先要让新的结点指向head后面的结点这样才能防止整个链表的内存被释放。之后再让head连接上新的结点即可。

4、insert_tail方法相对于头插的方法更加简单,只需要定义一个索引n让n遍历整个链表,最终n会索引到整个列表的最后一个元素,只需要让n.next指向new_node即可。

5、delete函数使用了双指针的方法,通过p,q两个指针一前一后的遍历,让p在前面遍历一旦发现了要找的元素,就让q直接跳过p让q的next索引到p的后面这样就可以删除选中结点。

以上是关于代码的解释有什么不足欢迎指出

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值