2.请编程实现一个对单链表进行基本操作的系统,主要包括表的创建、输入、查询、取值、插入、删除和输出等操作。(要求:可以采用带头结点和不带头结点的单链表)
时间: 2023-12-20 18:07:53 浏览: 63
单链表的操作
5星 · 资源好评率100%
以下是使用带头结点实现的单链表基本操作系统:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = Node()
def append(self, data):
new_node = Node(data)
current = self.head
while current.next != None:
current = current.next
current.next = new_node
def length(self):
current = self.head
total = 0
while current.next != None:
total += 1
current = current.next
return total
def display(self):
elements = []
current = self.head
while current.next != None:
current = current.next
elements.append(current.data)
print(elements)
def get(self, index):
if index >= self.length():
print("Error: 'Get' Index out of range!")
return None
current_idx = 0
current_node = self.head
while True:
current_node = current_node.next
if current_idx == index: return current_node.data
current_idx += 1
def delete(self, index):
if index >= self.length():
print("Error: 'Delete' Index out of range!")
return
current_idx = 0
current_node = self.head
while True:
last_node = current_node
current_node = current_node.next
if current_idx == index:
last_node.next = current_node.next
return
current_idx += 1
def insert(self, index, data):
if index >= self.length():
print("Error: 'Insert' Index out of range!")
return
current_idx = 0
current_node = self.head
while True:
last_node = current_node
current_node = current_node.next
if current_idx == index:
new_node = Node(data)
last_node.next = new_node
new_node.next = current_node
return
current_idx += 1
```
使用示例:
```python
# 创建一个带头结点的单链表
my_list = LinkedList()
# 在链表尾部追加元素
my_list.append(1)
my_list.append(2)
my_list.append(3)
# 输出链表元素
my_list.display() # [1, 2, 3]
# 查询元素
print(my_list.get(1)) # 2
# 删除元素
my_list.delete(1)
my_list.display() # [1, 3]
# 在指定位置插入元素
my_list.insert(1, 2)
my_list.display() # [1, 2, 3]
```
阅读全文