定义一个线性链表代码
时间: 2024-09-20 13:00:54 浏览: 42
定义一个线性链表通常涉及创建节点类和链表类。这里是一个简单的 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
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)