from typing import Any, Optional
class Node(object):
def __init__(self, value: Any, next: Optional["Node"]=None):
self.value = value
self.next = next
def __repr__(self):
return f"Node({self.value})"
class LinkedList(object):
def __init__(self):
self.head = None
def add_front(self, value):
# 在前端插入值,head重新指向
# 情况1:若为空链
if self.head is None:
self.head = Node(value)
# 情况2:若为非空链
else:
new_node = Node(value, self.head)
self.head = new_node
def add_rear(self, value):
# 在末端插入值,循环查找最后一个元素
# 情况1:若为空链
if self.head is None:
self.head = Node(value)
# 情况2:若为非空链
else:
current = self.head
while current.next is not None:
current = current.next
current.next = Node(value)
def __len__(self):
sum = 0
current = self.head
while current:
sum += 1
current = current.next
return sum
def del_front(self):
# 删除链首,即head重新指向
if self.head is None:
raise ValueError("The linkedlist is null!")
else:
self.head = self.head.next
def del_rear(self):
# 删除链尾
if self.head is None:
raise ValueError("The linkedlist is null!")
elif self.head.next is None:
self.head = None
else:
current = self.head
while current.next.next:
current = current.next
current.next = None
def isEmpty(self):
# 判断是否为空
return self.head is None
def __repr__(self):
if self.head is None:
return "Null LinkedList"
else:
node_list = []
node = self.head
while node:
node_list.append(f"Node({node.value})")
node = node.next
return '——>'.join(node_list)
def reverse(self):
# 链表的翻转
prev = None
current = self.head
while current.next:
next = current.next
current.next = prev
prev = current
current = next
current.next = prev
self.head = current
def insert(self, index, value):
# 插入某个链
current = self.head
new_node = Node(value)
if index == 0:
new_node.next = current
self.head = new_node
else:
for i in range(1, index):
current = current.next
if current is None:
raise IndexError("Index out of range")
next = current.next
new_node.next = next
current.next = new_node
def __getitem__(self, index):
current = self.head
if current is None:
raise IndexError("The Linked List is empty")
for i in range(index):
if current.next is None:
raise IndexError("Index out of range")
current = current.next
return current.value
def __setitem__(self, index, value):
current = self.head
if current is None:
raise IndexError("The Linked List is empty")
for i in range(index):
if current.next is None:
raise IndexError("Index out of range")
current = current.next
current.value = value
【链表】用python实现单向链表
最新推荐文章于 2023-08-14 16:14:55 发布