python self next_Python数据结构——链表(一)单链表

之前学C时学到可以通过指针指向某一节点实现空间上不连贯的单位逻辑上连贯,也就是所谓的链表,Python中不存在指针的概念,可以通过定义类来实现类似链表的效果。

写下来做个总结

定义节点

class node(object):

def __init__(self,item):

self.item = item

self.next = None

item代表存储的内容,next用来模拟指针。

创建单链表类

length:链表长度

head:链表头节点

count:现有节点数

class singlechainlist(object):

def __init__(self,length:int):

self.length = length

self.head = node(None)

self.count = 0

def __num_node(self,x:int):

self.count += x

def search(self,x:node): # search for the node and return the precvious node

if self.head.next == x:

return self.head

else:

temp = self.head.next

while temp.next != x:

temp = temp.next

return temp

def add_node(self,node:node): # add at the end of chain

if self.count == self.length:

print('cannot exceed max length')

else:

self.find_tail().next = node

self.__num_node(1)

def find_tail(self,x=None): # find the last node

if x is None:

x = self.head

if x.next is None:

return x

else:

temp = x.next

if temp.next is None:

return temp

else:

return self.find_tail(temp)

def del_node(self,x=None):

if self.head.next is None:

print('no node any more!')

else:

if x is None:

self.search(self.find_tail()).next=None

self.__num_node(-1)

else:

self.search(x).next = x.next

x = None

self.__num_node(-1)

def insert_node(self,x:node,y:node):

if self.count == self.length:

print('cannot exceed max length')

else:

if self.head.next is None:

self.head.next = y

self.__num_node(1)

else:

self.search(x).next = y

y.next = x

self.__num_node(1)

def get_chain(self):

chain = [self.head]

while chain[-1].next != None:

chain.append(chain[-1].next)

return chain

现在实现的功能:

在末尾加节点

在链表中插入节点

查找节点

删除节点

获取完整链表

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值