数据结构代码: 建立单向链表,实现初始化,插入,取值、查找、删除操作
时间: 2024-09-23 17:15:37 浏览: 58
在计算机科学中,数据结构是组织和存储数据的方式。这里以单向链表为例,它是一种基础的数据结构,每个节点包含数据和指向下一个节点的引用。以下是Python中对单向链表的一些基本操作的简单实现:
```python
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 初始化链表
def initialize(self):
self.head = None
# 插入节点
def insert(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 取值(获取头节点的值)
def get_value(self):
if self.head:
return self.head.value
else:
return None
# 查找特定值的节点
def find(self, target):
current = self.head
while current:
if current.value == target:
return current
current = current.next
return None
# 删除节点
def delete(self, value):
if not self.head:
return
if self.head.value == value:
self.head = self.head.next
return
current = self.head
prev = None
while current and current.value != value:
prev = current
current = current.next
if current is not None:
prev.next = current.next
```
阅读全文