创建一个由6个结点的单向链表,实现结点的增加、删除、查找、移动、遍历显示
时间: 2023-11-21 13:04:09 浏览: 83
单链表的创建、插入、删除、查找
5星 · 资源好评率100%
好的,我明白了。以下是关于创建一个由6个结点的单向链表的代码实现:
```python
# 定义链表节点类
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
# 定义链表类
class LinkedList:
def __init__(self):
self.head = None
# 实现节点的增加
def add_node(self, val):
new_node = ListNode(val)
if self.head is None:
self.head = new_node
else:
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = new_node
# 实现节点的删除
def delete_node(self, val):
curr = self.head
prev = None
while curr is not None:
if curr.val == val:
if prev is None:
self.head = curr.next
else:
prev.next = curr.next
return
prev = curr
curr = curr.next
# 实现节点的查找
def find_node(self, val):
curr = self.head
while curr is not None:
if curr.val == val:
return True
curr = curr.next
return False
# 实现节点的移动
def move_node(self, val, after_val):
curr = self.head
while curr is not None:
if curr.val == val:
after_node = self.find_node(after_val)
if after_node is None:
return False
else:
curr.next = after_node.next
after_node.next = curr
return True
curr = curr.next
return False
# 实现链表的遍历显示
def display_list(self):
curr = self.head
while curr is not None:
print(curr.val)
curr = curr.next
```
以上是一个简单的单向链表的实现,其中包括了节点的增加、删除、查找、移动和遍历显示。如果您有任何问题,请随时问我!
阅读全文