Python如何实现栈

69 阅读1分钟

Python如何实现栈

在 Python 中,栈(Stack)是一种后进先出(LIFO, Last In First Out)的数据结构。我们可以使用列表(list)来实现栈。下面分别用 append​ 方法和 insert​ 方法来实现栈的基本操作:压栈(push)和出栈(pop)。

  • 使用 append​ 方法实现栈时,元素被添加到列表的末尾,出栈时从列表的末尾移除元素。
  • 使用 insert​ 方法实现栈时,元素被插入到列表的开头,出栈时从列表的开头移除元素。

这两种方法都可以实现栈的基本功能,但在性能上有所不同。append​ 方法在列表末尾添加元素的时间复杂度为 O(1),而 insert​ 方法在列表开头插入元素的时间复杂度为 O(n),因为需要移动其他元素。

使用 append​ 方法实现栈

使用 append​ 方法可以将元素添加到列表的末尾,这符合栈的 LIFO 特性。

class StackWithAppend:
    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()
        else:
            raise IndexError("pop from empty stack")

    def is_empty(self):
        return len(self.stack) == 0

    def peek(self):
        if not self.is_empty():
            return self.stack[-1]
        else:
            raise IndexError("peek from empty stack")

    def size(self):
        return len(self.stack)

# 示例
stack = StackWithAppend()
stack.push('A')
stack.push('B')
stack.push('C')
print(stack.pop())  # 输出: C
print(stack.peek())  # 输出: B
print(stack.size())  # 输出: 2

使用 insert​ 方法实现栈

使用 insert​ 方法可以将元素插入到列表的指定位置。为了实现栈的 LIFO 特性,我们可以将元素插入到列表的开头(索引为 0 的位置)。

class StackWithInsert:
    def __init__(self):
        self.stack = []

    def push(self, item):
        self.stack.insert(0, item)

    def pop(self):
        if not self.is_empty():
            return self.stack.pop(0)
        else:
            raise IndexError("pop from empty stack")

    def is_empty(self):
        return len(self.stack) == 0

    def peek(self):
        if not self.is_empty():
            return self.stack[0]
        else:
            raise IndexError("peek from empty stack")

    def size(self):
        return len(self.stack)

# 示例
stack = StackWithInsert()
stack.push('A')
stack.push('B')
stack.push('C')
print(stack.pop())  # 输出: C
print(stack.peek())  # 输出: B
print(stack.size())  # 输出: 2