设计一个单链表的基本运算程序,并用相关数据进行测试
时间: 2024-09-21 10:06:24 浏览: 42
实现循环单链表的各种基本运算的算法
设计一个单链表的基本运算程序通常涉及以下几个步骤:
1. **定义链表结构**:首先创建一个节点类,包含一个数据字段和一个指向下一个节点的引用(指针)。
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
```
2. **链表类**:定义链表类,包括初始化、插入节点、删除节点、搜索和打印列表等基本操作。
```python
class LinkedList:
def __init__(self):
self.head = None
def append(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 insert_at(self, index, data):
if index < 0 or index > self.length():
return
new_node = Node(data)
if index == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
def delete(self, key):
if not self.head:
return
if self.head.data == key:
self.head = self.head.next
return
current = self.head
while current.next and current.next.data != key:
current = current.next
if current.next:
current.next = current.next.next
def search(self, key):
current = self.head
while current:
if current.data == key:
return True
current = current.next
return False
def print_list(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("List:", elements)
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
```
你可以通过以下方式进行测试:
```python
# 创建一个链表实例
my_list = LinkedList()
# 添加元素
my_list.append(1)
my_list.append(2)
my_list.insert_at(1, 3) # 插入 3 在索引 1
# 打印初始链表
my_list.print_list() # 输出: List: [1, 3, 2]
# 搜索和删除
print(my_list.search(3)) # 输出: True
my_list.delete(2)
my_list.print_list() # 输出: List: [1, 3]
# 验证长度
print(my_list.length()) # 输出: 2
```
阅读全文