python创建双链表_Python数据结构——链表(二)双链表

续之前的单链表

定义节点

class node(object):

def __init__(self,item):

self.item = item

self.next = None

self.pre = None

item代表存储的内容,next用来模拟指针指向后一个节点,pre用来模拟指针指向前一节点。

插入节点示意图

e7822df4d843

插入节点1.png

e7822df4d843

插入节点2.png

创建双链表类

length:链表长度

head:链表头节点

count:现有节点数

class bidirectchainlist(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,mode='b'):

'''

mode='b':search for the node and return the precvious node, backward

mode='f':search for the node and return the next node, forward

'''

if mode=='b':

if self.head.next == x:

return self.head

else:

temp = self.head.next

while temp.next != x:

temp = temp.next

return temp

elif mode=='f':

if self.find_tail() == x:

return x

elif self.find_tail().pre == x:

return self.find_tail()

else:

temp = self.find_tail().pre

while temp.pre != x:

temp = temp.pre

return temp

def add_node(self,node:node): # add at the end of chainself.search(x).next

if self.count == self.length:

print('cannot exceed max length')

else:

temp = self.find_tail()

self.find_tail().next = node

node.pre = temp

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:

temp = self.search(x)

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

x.next.pre = temp

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

y.pre = self.head

self.__num_node(1)

else:

temp = self.search(x)

temp.next = y

y.pre = temp

y.next = x

x.pre = y

self.__num_node(1)

def get_chain(self):

chain = [self.head]

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

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

return chain

支持双向搜索

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值