单链表各类基本运算代码
时间: 2024-09-26 12:14:37 浏览: 35
单链表是一种基础的数据结构,其节点包含数据和指向下一个节点的指针。以下是单链表的一些常见操作的简单代码示例,假设我们有一个Node类表示链表节点:
1. **创建链表头节点**:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
# 创建一个空链表
head = Node(None)
```
2. **添加新元素(在链表尾部)**:
```python
def append(head, data):
new_node = Node(data)
if head is None:
head = new_node
else:
current = head
while current.next is not None:
current = current.next
current.next = new_node
```
3. **删除元素(指定值)**:
```python
def delete(head, value):
if head is None or head.data == value:
head = head.next
return
previous = head
current = head.next
while current is not None:
if current.data == value:
previous.next = current.next
break
previous = current
current = current.next
```
4. **遍历链表**:
```python
def traverse(head):
current = head
while current is not None:
print(current.data, end=" -> ")
current = current.next
print("None")
```
5. **查找元素**:
```python
def search(head, value):
current = head
while current is not None:
if current.data == value:
return True
current = current.next
return False
```
阅读全文