Stack (stack) of commonly used data structures

1. Theory Introduction

        In the previous article, we introduced the heap in the data structure . As the saying goes, the stack is not divided into families. Let's continue to talk about the data structure of the stack. The stack is essentially a linear table with special requirements. Those interested can learn about the linear table in the data structure mentioned earlier . Since it is a linear table, it has two forms, one is linear storage (a contiguous memory space like an array), and the other is chain storage (a non-contiguous space like a linked list);

        The special requirement of the stack is LIFO (Last In First Out), yes, last in first out. Only the element at the top of the stack is allowed to be accessed. Remember the heap mentioned in the previous article? In essence, only the top element of the heap is often used. But the heap is a top pop based on the value size, and the stack is a top pop based on time sequence (the so-called top is the last moment element); generally speaking, the stack in memory is also implemented using the idea of ​​stack.

                            

 2. Code implementation

        In this article, we use a list in python to implement a stack. The basic idea is to directly append to the end of the list when no element is inserted, and directly use the pop method to return and delete the tail element when the element is popped. So the time complexity of insertion is O(1), and the time complexity of popup is O(n).

#-*- coding:utf-8 -*-
class Stack(object):
    def __init__(self):
        self.array = []
    #弹出栈顶的元素
    def pop(self):
        #pop方法默认弹出最后一个元素
        return  self.array.pop()
    #查看栈顶的元素
    def peek(self):
        return self.array[-1]
    #入栈,插入到最后一位
    def push(self,v):
        self.array.append(v)
    #查看栈的大小
    def get_size(self):
        return len(self.array)
    #判断栈是否 为空
    def is_empty(self):
        return self.array == []

3. Determine whether the brackets match

          One of the common scenarios of stack structure is to judge whether the left parenthesis and the right parenthesis match. Our realization idea is as follows: if it is a left parenthesis, push it to the stack, if it is a right parenthesis, pop the left parenthesis at the top of the stack; finally, if the stack is empty , Then the number of left and right parentheses are matched; if the right parenthesis appears first, the stack is empty at this time, and it is judged as a mismatch.

      Of course, in addition to bracket matching, we can also do a lot of matching work, this article uses this as an example!

def balance(str):
    stack = Stack()
    for i,v in enumerate(str):
        if v == '(':
            stack.push(v)
        elif v == ')':
            if stack.is_empty():
                return False
            else:
                stack.pop()
    return stack.is_empty()
str = '()))'
print(balance(str))

4. Summary

          This article describes the stack in commonly used data structures. The data structure is a kind of thought, a structure designed for specific tasks. The idea of ​​the stack is last-in, first-out. The time complexity of stacking is O(1) and the time complexity of popping is O(n). Because the top element of the stack is popped, the positions of other elements need to be changed.

5. Good poem recommendation

                 Do not go to Chang'an Road. But the mountain temple is reluctant to welcome it. Seek my happiness where the taste is tasteless, and live this life out of talent.
                 I would rather be me. Traveled all over the world but returned to farming. A true friend of one pine and one bamboo, a good brother from the mountain bird and the flower.

                                                                                                                                "Partridge Sky·Boshan Temple Works" Xin Qiji

  

Come on! Let's dance together!

 

Guess you like

Origin blog.csdn.net/gaobing1993/article/details/108782686