编写程序建立一个顺序表 逐个输出顺序表中所有元素的值
时间: 2024-12-16 21:25:58 浏览: 5
编写一个程序来创建并操作顺序表(也称为线性表),可以按照以下步骤进行,这里假设我们用Python为例:
```python
class Node:
def __init__(self, value):
self.value = value
self.next = None
class SequentialList:
def __init__(self):
self.head = None
def add_element(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def display_elements(self):
elements = []
current = self.head
while current:
elements.append(current.value)
current = current.next
for element in elements:
print(element)
# 使用示例
sequence_list = SequentialList()
sequence_list.add_element(1)
sequence_list.add_element(2)
sequence_list.add_element(3)
sequence_list.display_elements()
阅读全文