编写程序依次实现如下功能:初始化单链表依次采用尾插法插入a,b,c,d,e元素输出单链表输出单链表的长度判断单链表是否为空输出单链表的第三个元素输出元素a的位置在第4个元素的位置上插入f元素输出单链表删除单链表的第3个元素输出单链表
时间: 2024-12-16 12:27:45 浏览: 11
首先,让我们分步骤地编写一个简单的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):
if not self.head:
self.head = Node(data)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(data)
# 输出链表
def print_list(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print(elements)
# 计算链表长度
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
# 判断链表是否为空
def is_empty(self):
return self.head is None
# 获取指定位置的元素
def get_element_at_position(self, position):
index = 0
current = self.head
while current and index < position:
current = current.next
index += 1
if current:
return current.data
else:
raise IndexError("Position out of range")
# 插入新元素到指定位置
def insert_at_position(self, data, position):
new_node = Node(data)
if position == 0:
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(position - 1):
if not current.next:
raise IndexError("Invalid position")
current = current.next
new_node.next = current.next
current.next = new_node
# 删除链表的指定元素
def delete_at_position(self, position):
if position == 0:
self.head = self.head.next
else:
current = self.head
for _ in range(position - 1):
if not current.next:
raise IndexError("Invalid position")
current = current.next
current.next = current.next.next
# 示例操作
llist = LinkedList()
llist.append('a')
llist.append('b')
llist.append('c')
llist.append('d')
llist.append('e')
llist.print_list() # 打印链表
print(llist.length()) # 输出链表长度
print(llist.is_empty()) # 判断是否为空
print(llist.get_element_at_position(3)) # 输出第三个元素
llist.insert_at_position('f', 4) # 插入元素f
llist.delete_at_position(2) # 删除第3个元素
llist.print_list() # 输出更新后的链表
```
请注意,上述代码示例仅适用于简单线性链表,并假设所有操作都有效。实际应用中需要处理异常情况,例如索引越界等错误。
阅读全文