欢迎访问宙启技术站
智能推送

实现基本数据结构的Python代码示例

发布时间:2023-12-04 14:54:28

以下是基本数据结构的Python代码示例及其使用示例:

1. 数组(Array):

# 创建一个空数组
arr = []

# 在数组的末尾添加元素
arr.append(1)
arr.append(2)
arr.append(3)

# 访问数组元素
print(arr[0])  # 输出: 1
print(arr[2])  # 输出: 3

# 遍历数组
for element in arr:
    print(element)

# 输出:
# 1
# 2
# 3

2. 链表(Linked List):

# 定义链表节点类
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

# 创建链表
head = Node(1)
second = Node(2)
third = Node(3)

# 连接链表节点
head.next = second
second.next = third

# 遍历链表
current = head
while current:
    print(current.data)
    current = current.next

# 输出:
# 1
# 2
# 3

3. 栈(Stack):

# 创建一个空栈
stack = []

# 在栈顶添加元素
stack.append(1)
stack.append(2)
stack.append(3)

# 弹出栈顶元素
print(stack.pop())  # 输出: 3

# 访问栈顶元素
print(stack[-1])  # 输出: 2

# 遍历栈
for element in reversed(stack):
    print(element)

# 输出:
# 2
# 1

4. 队列(Queue):

# 导入队列模块
from queue import Queue

# 创建一个空队列
queue = Queue()

# 在队尾添加元素
queue.put(1)
queue.put(2)
queue.put(3)

# 弹出队首元素
print(queue.get())  # 输出: 1

# 遍历队列
while not queue.empty():
    print(queue.get())

# 输出:
# 2
# 3

5. 字典(Dictionary):

# 创建一个空字典
my_dict = {}

# 添加键值对
my_dict["name"] = "Alice"
my_dict["age"] = 25

# 访问字典元素
print(my_dict["name"])  # 输出: Alice

# 遍历字典
for key, value in my_dict.items():
    print(key, value)

# 输出:
# name Alice
# age 25

这些是基本数据结构的Python代码示例及其使用示例。你可以根据自己的需要使用这些示例来实现不同的基本数据结构。