python怎么创建单向链表
时间: 2023-11-13 12:55:16 浏览: 82
python实现单向链表详解
要创建单向链表,可以先定义一个节点类,然后在节点类中定义节点的值和指向下一个节点的指针。接着,可以定义一个链表类,其中包含头节点和尾节点,以及一些方法来操作链表,比如添加节点、删除节点等。下面是一个简单的示例代码:
```python
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def add_node(self, val):
new_node = Node(val)
if not self.head:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
def remove_node(self, val):
if not self.head:
return
if self.head.val == val:
self.head = self.head.next
if not self.head:
self.tail = None
return
prev_node = self.head
curr_node = self.head.next
while curr_node:
if curr_node.val == val:
prev_node.next = curr_node.next
if not curr_node.next:
self.tail = prev_node
return
prev_node = curr_node
curr_node = curr_node.next
def print_list(self):
curr_node = self.head
while curr_node:
print(curr_node.val, end=' ')
curr_node = curr_node.next
print()
# 示例代码的使用方法:
linked_list = LinkedList()
linked_list.add_node(1)
linked_list.add_node(2)
linked_list.add_node(3)
linked_list.print_list() # 输出:1 2 3
linked_list.remove_node(2)
linked_list.print_list() # 输出:1 3
```
阅读全文