python单链表使用
时间: 2023-07-20 17:26:21 浏览: 88
要使用Python实现单链表,可以定义一个Node类表示链表中的每个节点,以及一个LinkedList类表示整个表。下面是一个简单的单链表的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 is not None:
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
```
这个实现包括了一些常用的操作,例如添加节点、在节点前插入节点、在节点后插入节点、删除节点和打印整个链表。可以使用以下代码测试这个实现:
```
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
```
阅读全文