# Python链表的实现

# 节点类
class Node:
def __init__(self,data):
self.data = data
self.next = None

def __str__(self):
return self.data

# 链表类
def __init__(self):
self.length = 0

# 创建链表
def creat(self):

# 判断链表是否为空
def is_empty(self):
return True
else:
return False

# 清空链表
def clear_list(self):
self.length = 0

# 在尾部添加节点
def append(self, this_node):
if self.is_empty():
else:
while node.next:
node = node.next
node.next = this_node
self.length += 1

# 删除尾部节点
def remove(self):
if self.is_empty():
print('链表为空')
return False
else:
while node.next:
node = node.next
if node.next.next is None:
node.next = None
self.length -= 1

# 获取链表长度
def get_length(self):
print(self.length)

# 插入节点
def insert(self, position, this_node):
if position == 1 and self.length == 0:
self.append(this_node)
if position > self.length:
print('超出链表长度')
return False
else:
index = 0
while node.next:
index += 1
if index == position:
this_node.next = node.next
node.next = this_node
self.length += 1
return True
node = node.next

# 按在链表中的位置删除节点
def delete_by_position(self, position):
if self.is_empty():
print('列表为空')
return False
else:
if position > self.length:
print('超过链表长度')
return False
index = 0
while node.next:
index += 1
if index == position:
node.next = node.next.next
self.length -= 1
return True
node = node.next

# 按值删除节点
def delete_by_value(self, value):
if self.is_empty():
print('列表为空')
return False
else:
while node.next:
if node.next.data == value:
node.next = node.next.next
self.length -= 1
return True
node = node.next
print('此值不在链表中')
return False

# 对链表进行遍历
def traverse(self):
if self.is_empty():
print("链表为空")
return False
else:
print(node.data, end='')
while node.next:
node = node.next
print("--> {}".format(node.data), end='')
print()
return True

Node1 = Node(1)
Node2 = Node(2)
Node3 = Node(3)
# 初始化空链表
Test_List.creat()
# 添加节点
Test_List.append(Node1)
Test_List.append(Node2)
Test_List.append(Node3)
# 测试
Test_List.traverse()
Test_List.insert(2, Node('test'))
Test_List.traverse()
Test_List.delete_by_position(4)
Test_List.traverse()
Test_List.delete_by_value('test')
Test_List.traverse()

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120