采用链式存储结构,创建一个单链表,实现图书信息的存储,并能完成如下操作 1.建立单链表(头插法或尾插法);2.单链表的输出; 3.单链表的插入操作;4.单链表的删除操作; 5.求单链表的长度;6.取表中第i个元素; 7.在表中査找值为e的元素位置。
时间: 2024-11-04 11:14:54 浏览: 6
数据结构(C语言)用单链表存储一元多项式并实现两个多项式的相加运算.doc
5星 · 资源好评率100%
在采用链式存储结构的情况下,我们可以创建一个简单的单链表用于存储图书信息。这里是一个基础的Python实现:
```python
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
# 1. 建立单链表 - 尾插法
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)
# 2. 单链表的输出
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print("Book List:", elements)
# 3. 插入操作 - 指定位置插入
def insert_at_position(self, position, data):
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 current.next is not None:
current = current.next
if current.next is not None:
new_node.next = current.next
current.next = new_node
# 4. 删除操作 - 删除指定节点的数据
def delete_data(self, data):
if self.head and self.head.data == data:
self.head = self.head.next
else:
current = self.head
prev = None
while current:
if current.data == data:
prev.next = current.next
break
prev = current
current = current.next
# 5. 求单链表的长度
def length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
# 6. 取表中第i个元素
def get_element_by_index(self, index):
current = self.head
for _ in range(index):
if current is None:
raise IndexError("Index out of range")
current = current.next
return current.data if current else None
# 7. 查找值为e的元素位置
def find_element(self, e):
current = self.head
position = 0
while current:
if current.data == e:
return position
current = current.next
position += 1
return -1 # 如果找不到,返回-1表示未找到
# 示例:
book_list = LinkedList()
book_list.append('Book1')
book_list.append('Book2')
# ...更多操作...
```
阅读全文