【栈结构】

(Stack)是一种线性数据结构,特点是后进先出(Last-In-First-Out,LIFO)。

基本操作

栈的基本操作包括:

  • push:将元素压入栈顶
  • pop:将栈顶元素弹出
  • top:获取栈顶元素但不弹出
  • isEmpty:判断栈是否为空
  • size:获取栈的元素个数

实现方式

基于顺序存储

class ArrayStack:
    def __init__(self, capacity):
        self._capacity = capacity
        self._data = [None] * self._capacity
        self._size = 0

    def push(self, val):
        if self._size == self._capacity:
            self._expand_capacity()
        self._data[self._size] = val
        self._size += 1

    def _expand_capacity(self):
        self._capacity *= 2
        new_data = [None] * self._capacity
        for i in range(self._size):
            new_data[i] = self._data[i]
        self._data = new_data

    def pop(self):
        if self.is_empty():
            raise Exception("stack is empty")
        self._size -= 1
        return self._data[self._size]

    def is_empty(self):
        return self._size == 0

    def top(self):
        if self.is_empty():
            raise Exception("stack is empty")
        return self._data[self._size - 1]

    def size(self):
        return self._size

基于链式存储

class StackNode:
    def __init__(self, val):
        self.val = val
        self.next = None


class ChainStack:
    def __init__(self):
        self._top_node = None
        self._size = 0

    def push(self, val):
        new_node = StackNode(val)
        new_node.next = self._top_node
        self._top_node = new_node
        self._size += 1

    def pop(self):
        if self.is_empty():
            raise Exception("stack is empty")
        val = self._top_node.val
        self._top_node = self._top_node.next
        self._size -= 1
        return val

    def is_empty(self):
        return self._top_node is None

    def top(self):
        if self.is_empty():
            raise Exception("stack is empty")
        return self._top_node.val

    def size(self):
        return self._size

应用场景

  • 表达式求值
  • 函数调用堆栈
  • 括号匹配
  • 迷宫求解
  • 浏览器前进后退历史记录

你可能感兴趣的:(数据结构,数据结构)