创建一个由6个结点的单向链表,实现结点的增加、删除、查找、移动、遍历显示等功能。
时间: 2023-12-21 14:03:24 浏览: 31
c代码-//带表头结点的单向链表
以下是基于 Python3 的单向链表实现,包括结点的增加、删除、查找、移动、遍历等功能:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 添加结点
def add_node(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
# 删除结点
def delete_node(self, data):
if self.head is None:
return
if self.head.data == data:
self.head = self.head.next
return
current = self.head
while current.next:
if current.next.data == data:
current.next = current.next.next
return
current = current.next
# 查找结点
def find_node(self, data):
if self.head is None:
return False
current = self.head
while current:
if current.data == data:
return True
current = current.next
return False
# 移动结点
def move_node(self, data, index):
if self.head is None:
return
if self.head.data == data:
current = self.head
self.head = self.head.next
else:
current = self.head
while current.next:
if current.next.data == data:
current = current.next
break
current = current.next
if current is None:
return
tmp = current
for i in range(index):
if tmp.next is None:
return
tmp = tmp.next
current.next = tmp.next
tmp.next = current
# 遍历链表
def traverse(self):
if self.head is None:
return
current = self.head
while current:
print(current.data, end=' ')
current = current.next
print()
```
以下是测试代码:
```python
ll = LinkedList()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)
ll.add_node(4)
ll.add_node(5)
ll.add_node(6)
ll.traverse() # 输出:1 2 3 4 5 6
ll.delete_node(3)
ll.traverse() # 输出:1 2 4 5 6
print(ll.find_node(4)) # 输出:True
print(ll.find_node(3)) # 输出:False
ll.move_node(4, 2)
ll.traverse() # 输出:1 2 5 4 6
```
以上代码实现了一个由6个结点的单向链表,并且对其进行了添加、删除、查找、移动、遍历等操作。
阅读全文