python实现数据结构中链表的代码
时间: 2023-11-26 22:09:00 浏览: 96
下面是 Python 实现单向链表的代码:
```python
class Node:
def __init__(self, data=None):
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
```
上述代码实现了链表的基本操作,包括添加节点、插入节点、删除节点以及打印链表。你可以通过下面的代码测试上述代码:
```python
linked_list = LinkedList()
linked_list.append("A")
linked_list.append("B")
linked_list.append("C")
linked_list.prepend("D")
linked_list.insert_after_node(linked_list.head.next, "E")
linked_list.delete_node("B")
linked_list.print_list() #输出 D A E C
```
阅读全文