双向链表是除头和尾以外,头指针指向前一节点,尾指针指向后一节点
python实现
#定义双向链表
class ListNode():
def __init__(self,data):
self.head = None
self.data = data
self.next = None
#判断是否为空
def isempty(self):
return self.data == None
#尾部插入元素
def nodes_tail(self,data):
if isempty(self):
self.data = data
else:
node = ListNode(None)
node.data = data
p = self
while p.next is not None:
p = p.next
p.next = node
node.head = p
#首部插入元素
def nodes_head(self,data):
if isempty(self):
self.data = data
return self
else:
node = ListNode(None)
node.data = data
node.next = self
self.head = node
return node
#在中间插入节点
def nodes_insert(self,data,num):
if isempty(self) and num == 1:
self.data = data
else:
node = ListNode(None)
node.data = data
p = self
num = num-2
while num and p.next is not None:
print(num)
p = p.next
num = num - 1
node.next = p.next
node.head = p
p.next.head = node
p.next = node
#删除中间节点元素
def nodes_remove(self,num):
if num == 1:
return False
else:
p = self
num = num - 1
while num and p.next is not None:
p = p.next
num -= 1
if num == 0:
p.next.head = p.head
p.head.next = p.next
return True
else:
return False
if __name__ == '__main__':
nodelist = ListNode(None)
for i in range(5):
nodes_tail(nodelist,i)
nodelist = nodes_head(nodelist,10)
nodes_insert(nodelist,9,2)
nodes_remove(nodelist,2)
p = nodelist
#正序输出
while True:
print(p.data)
if p.next == None:
break
else:
p = p.next
#逆序输出
'''
while True:
print(p.data)
if p.head == None:
break
else:
p = p.head
'''