数据结构完整代码 建立单向链表,实现初始化,插入,取值、查找、删除操作
时间: 2024-09-23 18:15:31 浏览: 46
数据结构中的单向链表是一种基础的数据结构,它由节点组成,每个节点包含两个部分:数据域(存储数据)和指针域(指向下一个节点)。以下是使用Python实现单向链表的基本操作:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 初始化空链表
def initialize(self):
self.head = None
# 插入节点到链表开头
def insert_at_start(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# 插入节点到链表尾部
def insert_at_end(self, data):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)
# 获取指定索引处的节点值(仅适用于整数索引)
def get_value(self, index):
if index < 0 or not self.head:
return None
current = self.head
for _ in range(index):
if not current:
break
current = current.next
return current.data if current else None
# 查找特定值
def search(self, value):
current = self.head
while current:
if current.data == value:
return True
current = current.next
return False
# 删除第一个匹配的节点(如果存在)
def delete(self, value):
if not self.head:
return
if self.head.data == value:
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != value:
current = current.next
if current.next:
current.next = current.next.next
# 示例操作
linked_list = LinkedList()
linked_list.initialize()
linked_list.insert_at_start(1) # 插入数字1在最前面
linked_list.insert_at_end(2) # 插入数字2在最后面
print(linked_list.get_value(0)) # 输出:1
print(linked_list.search(2)) # 输出:True
linked_list.delete(1) # 删除值为1的节点
阅读全文