一个实现单链表基本操作的完整代码
时间: 2024-09-30 16:07:32 浏览: 45
在许多编程语言中,特别是像Python、C++或Java这样的面向对象语言中,创建一个简单的单链表并实现常见的插入、删除和遍历操作是一个基础练习。这里我给出一个使用Python的例子:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 插入节点到链表头部
def insert_at_start(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
new_node.next = self.head
self.head = new_node
# 插入节点到链表尾部
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除指定值的第一个节点
def delete(self, value):
if self.head and self.head.data == value:
self.head = self.head.next
else:
current = self.head
prev = None
while current and current.data != value:
prev = current
current = current.next
if current:
prev.next = current.next
# 遍历链表并打印所有元素
def print_list(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# 使用示例
my_list = LinkedList()
my_list.insert_at_start(5)
my_list.append(10)
my_list.insert_at_start(3)
my_list.print_list() # 输出: 3 -> 5 -> 10 -> None
my_list.delete(5)
my_list.print_list() # 输出: 3 -> 10 -> None
```
阅读全文