当前位置:实例文章 » HTML/CSS实例» [文章]【数据结构与算法】栈的实现(顺序存储)

【数据结构与算法】栈的实现(顺序存储)

发布人:shili8 发布时间:2025-01-06 19:34 阅读次数:0

**栈的实现(顺序存储)**

栈是一种线性数据结构,它遵循后进先出(LIFO)的原则,即最后添加的元素将最先被移除。栈可以用来模拟递归过程,或者在需要后进先出的场景中使用。

**栈的基本操作**

栈支持以下基本操作:

* `push(item)`: 将一个新元素添加到栈顶。
* `pop()`: 移除并返回栈顶元素。
* `peek()`: 返回栈顶元素,但不移除它。
* `isEmpty()`: 检查栈是否为空。
* `size()`: 返回栈中元素的数量。

**顺序存储实现**

我们将使用一个数组来实现栈。该数组将作为栈的底层数据结构,用于存储元素。

class Stack:
 def __init__(self, max_size):
 """
 Initializes a new stack with the given maximum size.

 :param max_size: The maximum number of elements that can be stored in the stack.
 """
 self.max_size = max_size self.top = -1 # Initialize top index to -1, indicating an empty stack self.items = [None] * max_size # Create a list with max_size elements def push(self, item):
 """
 Adds a new element to the top of the stack.

 :param item: The element to be added.
 :raises IndexError: If the stack is full (i.e., its size equals max_size).
 """
 if self.top == self.max_size -1:
 raise IndexError("Stack is full")
 self.top +=1 self.items[self.top] = item def pop(self):
 """
 Removes and returns the top element from the stack.

 :return: The removed element.
 :raises IndexError: If the stack is empty (i.e., its size equals0).
 """
 if self.isEmpty():
 raise IndexError("Stack is empty")
 item = self.items[self.top]
 self.items[self.top] = None self.top -=1 return item def peek(self):
 """
 Returns the top element from the stack without removing it.

 :return: The top element.
 :raises IndexError: If the stack is empty (i.e., its size equals0).
 """
 if self.isEmpty():
 raise IndexError("Stack is empty")
 return self.items[self.top]

 def isEmpty(self):
 """
 Checks whether the stack is empty.

 :return: True if the stack is empty, False otherwise.
 """
 return self.top == -1 def size(self):
 """
 Returns the number of elements in the stack.

 :return: The size of the stack.
 """
 return self.top +1


**示例代码**

# Create a new stack with a maximum size of5stack = Stack(5)

# Push some elements onto the stackstack.push(10)
stack.push(20)
stack.push(30)

# Print the top element (peek)
print(stack.peek()) # Output:30# Pop an element from the stack and print itprint(stack.pop()) # Output:30# Check if the stack is emptyprint(stack.isEmpty()) # Output: False# Get the size of the stackprint(stack.size()) # Output:2# Try to pop an element from an empty stack (raises IndexError)
try:
 print(stack.pop())
except IndexError as e:
 print(e) # Output: Stack is empty


**总结**

在本文中,我们实现了一个栈的顺序存储版本,支持基本操作,如push、pop、peek、isEmpty和size。我们使用一个数组来存储元素,并提供示例代码来演示这些操作的使用。

其他信息

其他资源

Top