定义一个线性链表代码
时间: 2024-09-20 15:00:54 浏览: 33
线性链表逆置_设有一线性表_线性链表逆置_
定义一个线性链表通常涉及创建节点类和链表类。这里是一个简单的 Python 示例:
```python
# 首先定义链表节点类 Node
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
# 然后定义链表类 LinkedList
class LinkedList:
def __init__(self):
self.head = None
# 插入节点到链表头部
def insert_at_start(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# 插入节点到链表尾部
def append(self, data):
if not self.head:
self.head = Node(data)
return
current = self.head
while current.next:
current = current.next
current.next = Node(data)
# 查找特定值并返回该节点
def find(self, key):
current = self.head
while current and current.data != key:
current = current.next
return current
# 删除节点
def delete(self, key):
if not self.head:
return
if self.head.data == key:
self.head = self.head.next
return
prev = None
current = self.head
while current and current.data != key:
prev = current
current = current.next
if current is None:
return
prev.next = current.next
# 使用示例
my_list = LinkedList()
my_list.insert_at_start(1) # 在链表头插入数字1
my_list.append(2) # 在链表尾部插入数字2
```
阅读全文