用 python实现链表
时间: 2023-09-23 10:04:56 浏览: 86
链表是一种常用的数据结构,可以用 Python 实现。下面是一个简单的链表实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_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):
curr_node = self.head
if curr_node and curr_node.data == key:
self.head = curr_node.next
curr_node = None
return
prev_node = None
while curr_node and curr_node.data != key:
prev_node = curr_node
curr_node = curr_node.next
if curr_node is None:
return
prev_node.next = curr_node.next
curr_node = None
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.data)
curr_node = curr_node.next
```
这个链表类包含了 Node 类和 LinkedList 类。Node 类表示链表中的一个节点,包含了数据和指向下一个节点的指针。LinkedList 类包含了链表的头节点 head,以及各种方法来操作链表,如 append、prepend、insert_after_node、delete_node 和 print_list。
下面是一个简单的测试:
```python
llist = LinkedList()
llist.append("A")
llist.append("B")
llist.append("C")
llist.append("D")
llist.prepend("E")
llist.insert_after_node(llist.head.next, "F")
llist.delete_node("B")
llist.print_list()
```
输出结果:
```
E
A
F
C
D
```
阅读全文