编写程序依次实现如下功能: 初始化单链表 依次采用尾插法插入a,b,c,d,e元素 输出单链表 输出单链表的长度 判断单链表是否为空 输出单链表的第三个元素 输出元素a的位置 在第4个元素的位置上插入f元素 输出单链表 删除单链表的第 3个元素 输出单链表
时间: 2024-12-16 10:28:45 浏览: 7
首先,让我们了解如何在Python中编写一个简单的单链表数据结构以及实现上述功能:
```python
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 初始化链表
def initialize(self):
if not self.head:
self.head = Node()
# 尾插法插入节点
def insert_at_end(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
# 输出链表
def print_list(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("链表:", elements)
# 计算链表长度
def get_length(self):
length = 0
current = self.head
while current:
length += 1
current = current.next
return length
# 判断链表是否为空
def is_empty(self):
return self.head is None
# 获取特定位置的元素
def find_element(self, index):
current = self.head
for _ in range(index):
if not current:
return None
current = current.next
return current.data if current else None
# 插入元素到指定位置
def insert_at_position(self, data, position):
if position == 0:
new_node = Node(data)
new_node.next = self.head
self.head = new_node
else:
current = self.head
for _ in range(position - 1):
if not current.next:
break
current = current.next
if current:
new_node = Node(data)
new_node.next = current.next
current.next = new_node
# 删除链表的第n个元素
def delete_nth(self, n):
if n == 0:
self.head = self.head.next
return
current = self.head
count = 1
while current and count < n:
prev = current
current = current.next
count += 1
if current:
prev.next = current.next
# 实例化并操作链表
ll = LinkedList()
ll.initialize()
ll.insert_at_end('a')
ll.insert_at_end('b')
ll.insert_at_end('c')
ll.insert_at_end('d')
ll.insert_at_end('e')
ll.print_list() # 输出: ['a', 'b', 'c', 'd', 'e']
print(f"链表长度: {ll.get_length()}")
print("判断链表是否为空:", ll.is_empty()) # 输出: False
print("第三个元素:", ll.find_element(2)) # 输出: 'c'
position_a = ll.find_element('a')
if position_a:
print(f"元素'a'的位置: {position_a}")
ll.insert_at_position('f', 4)
ll.print_list() # 输出: ['a', 'b', 'c', 'd', 'f', 'e']
ll.delete_nth(2) # 删除第三个元素
ll.print_list() # 输出: ['a', 'b', 'd', 'f', 'e']
```
阅读全文