python实现单向链表
# 节点类class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
def __str__(self):
return str(self.data)
# 链表类
class LinkedList:
def __init__(self):
self.head = None
self.length = 0
# 链表尾部append数据
def append(self, data):
node = Node(data)
if self.head is None: # head 未空,则此时链表为空,直接将新节点赋给self.head
self.head = node
else: # head 不为空
current = self.head
index = 0
while current.next: # 当前元素的下个元素是否为空
current = current.next
current.next = node
self.length += 1
# 某一位置插入节点
def insert(self, pos, data):
if pos < 0 or pos > self.length:
raise IndexError
new_node = Node(data) # 创建新的节点
# pos 为 0时
if pos == 0: # 插入到第一个位置,因为有head所以需要单独处理
new_node.next = self.head
self.head = new_node
self.length += 1
return
# pos不为0时
count = 0 # 记录遍历过的节点数
previous = None # 当前节点的前一个节点
current = self.head # 当前节点,从第一个节点开始遍历,所以默认为head
while count < pos: # 遍历到pos的前一个节点
count += 1
previous = current
current = current.next
previous.next = new_node # 循环结束后,将新的节点赋给previous.next
new_node.next = current # 将当前节点赋给 new_node.next
self.length += 1
# integer -- return first index of value.
def index(self, value) -> int:
index = 0
current = self.head
while current:
if current.data == value:
return index
current = current.next
index += 1
return -1
# index -> value
def valueof(self, index):
count = 0
current = self.head
while current:
if index == count:
return current.data
current = current.next
count += 1
return ''
# 移除某一个节点
def remove(self, value):
current = self.head
previous = None
index = 0
# 分两种情况 1、移除的节点是第一个节点(index=0), 2、移除的节点不是第一个节点(index !=0)
while current:
if current.data == value:
print('remove')
if index == 0:
self.head = current.next
else:
previous.next = current.next
return
previous = current
current = current.next
def update(self, index, new_value):
current = self.head
count = 0
while current:
if index == count:
current.data = new_value
return current.data
current = current.data
def __str__(self):
tostr = 'LinkedList { '
current = self.head
while current:
tostr = tostr + str(current) + " "
current = current.next
return tostr + '}'
# 测试代码
linklist = LinkedList()
linklist.append('1')
linklist.append('2')
linklist.append('3')
linklist.append('4')
linklist.append('5')
linklist.insert(0, 'a')
print(linklist)
print(linklist.length)
print(linklist.index('3'))
print(linklist.valueof(1))
print(linklist)
linklist.remove('a')
print(linklist)
print(linklist.update(0, 'b'))
print(linklist)
print(linklist.update(0, 'c'))
print(linklist)
以上是 python实现单向链表 的全部内容, 来源链接: utcz.com/z/389527.html