Data Structures and Algorithms (6) - Stack Stack

  • Basic definitions

What is the stack: the stack there is a set of data items order. In the stack, added, and removed items are only occur at the same end, this end of the call stack (Top), the other end of the stack, no operation is called a bottom (base).

Features: LIFO, last-out

  • The basic operation of the stack

We should know that there is no stack in python, but we can simulate a stack.

First, some of the basic operation of the stack we need to define:

Stack() Create an empty stack, it does not contain any data item
push(item) The item added to the stack, no return value
pop() The top of the stack data item is removed and returned, the stack has been modified
peek() View stack data items, return items without removing the top of the stack, and does not modify the stack
isEmpty() Returns whether the stack is empty
size() Return stack in the number of data items

 

 

 

 

 

 

 

 

Here, we can implement a stack with a list of operation types:

. 1  class Stack:
 2      '' ' 
. 3      their own definition of a stack
 4    the stack is a trailing end, the trailing end may be set to top of the stack
 . 5      ' '' 
. 6      DEF  the __init__ (Self):
 . 7          self.items = []
 . 8      DEF isEmpty (Self):
 . 9          return self.items == []
 10      DEF Push (Self, Item):
 . 11          self.items.append (Item)
 12 is      DEF POP (Self):
 13 is          self.items.pop ()
 14      DEF PEEK (Self):
 15          return self.items [len (self.items) -1 ]
16     def size(self):
17         return len(self.items)
18 if __name__ == '__main__':
19     s = Stack()
20     s.push('1')
21     s.push('a')
22     print(s.isEmpty())
23     print(s.peek())
24     print(s.size())
1 [out]:
2 False
3 a
4 2
5 
6 Process finished with exit code 0

 

  • Stack of applications
  1. Simple matching brackets

Task: to match the corresponding left and right parentheses, brackets construct a matching algorithm. From left to right scan brackets, the latest open left parenthesis, right parenthesis should match the first encounter 

flow chart:

 

 

 Code:

 1 from Stack import Stack
 2 def parChecker(symbolString):
 3     s = Stack()
 4     balanced = True
 5     index = 0
 6     while index < len(symbolString) and balanced:
 7         symbol = symbolString[index]
 8         if symbol == "(":
 9             s.push(symbol)
10         else:
11             if s.isEmpty():
12                 balanced = False
13             else:
14                 s.pop()
15         index = index + 1
16     if balanced and s.isEmpty():
17         return True
18     else:
19         return False
20 print(parChecker('((()))))'))
21 print(parChecker('(((())))'))
[OUT]:
1
False 2 True 3 4 Process finished with exit code 0

In practice, however, the bracket is often more complex, such as {} () []

Reference: https://www.bilibili.com/video/BV1QJ411w7bB?p=17

 

Guess you like

Origin www.cnblogs.com/yeshengCqupt/p/12571924.html