用python代码写一个单链表并测试单链表的功能
时间: 2023-05-30 14:03:53 浏览: 138
以下是一个简单的单链表实现:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
current_node = self.head
while current_node:
print(current_node.data)
current_node = current_node.next
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current_node = self.head
while current_node.next:
current_node = current_node.next
current_node.next = new_node
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self, prev_node, data):
if not prev_node:
print("Previous node is not in the list")
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
def delete_node(self, key):
current_node = self.head
if current_node and current_node.data == key:
self.head = current_node.next
current_node = None
return
prev_node = None
while current_node and current_node.data != key:
prev_node = current_node
current_node = current_node.next
if current_node is None:
return
prev_node.next = current_node.next
current_node = None
```
测试单链表的功能:
```python
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(4)
linked_list.prepend(0)
linked_list.insert_after_node(linked_list.head.next, 1.5)
linked_list.delete_node(3)
linked_list.print_list()
```
输出结果:
```
0
1
1.5
2
4
```
阅读全文