栈(Stack)是一个数据集合,可以理解为只能在一端进行插入或删除操作的列表
栈的特点:后进先出LIFO(last-in,first-out)
栈的概念:栈顶,栈底
基本操作:
- 进栈(压栈):push
- 出栈:pop
- 取栈顶:gettop
class Stack: def __init__(self): self.stack = [] def push(self, element): self.stack.append(element) def pop(self): return self.stack.pop() @property def is_empty(self): return len(self.stack) == 0 def get_top(self): if not self.is_empty: return self.stack[-1] return None
括号匹配问题:给定一个字符串,其中包括小括号,中括号,大括号,验证括号是否匹配
class Stack: def __init__(self): self.stack = [] def push(self, element): self.stack.append(element) def pop(self): return self.stack.pop() @property def is_empty(self): return len(self.stack) == 0 def get_top(self): if not self.is_empty: return self.stack[-1] return None def brace_match(s): match = {')':'(',']':'[','}':'{'} stack = Stack() for ch in s: if ch in match.values(): stack.push(ch) elif ch in match.keys(): if stack.is_empty: #当栈为空,多了个右括号 return False elif match[ch] != stack.get_top(): #右括号和栈顶不匹配 return False else: stack.pop() if not stack.is_empty: #最后栈不为空,说明 有括号没匹配上 return False return True s = "[()({}[])]]" ret = brace_match(s) print(ret)
利用栈实现深度优先走迷宫
maze = [ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 1, 0, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 0, 0, 0, 1], [1, 0, 0, 0, 1, 0, 0, 0, 0, 1], [1, 0, 1, 0, 0, 0, 1, 0, 0, 1], [1, 0, 1, 1, 1, 0, 1, 1, 0, 1], [1, 1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] ] dirs = [ lambda x,y: (x+1,y), lambda x,y: (x-1,y), lambda x,y: (x,y-1), lambda x,y: (x,y+1) ] def maze_path(x1,y1,x2,y2): stack = [] stack.append((x1, y1)) while(len(stack)>0): curNode = stack[-1] # 当前的节点 if curNode[0] == x2 and curNode[1] == y2: # 走到终点了 for p in stack: print(p) return True # x,y 四个方向 x-1,y; x+1,y; x,y-1; x,y+1 for dir in dirs: nextNode = dir(curNode[0], curNode[1]) # 如果下一个节点能走 if maze[nextNode[0]][nextNode[1]] == 0: stack.append(nextNode) maze[nextNode[0]][nextNode[1]] = 2 # 2表示为已经走过 break else: # maze[nextNode[0]][nextNode[1]] = 2 stack.pop() else: print("没有路") return False maze_path(1,1,8,8)