栈
只能在一端进行插入或删除操作的列表
特点:后进先出LIFO(last-in,first-out)
栈的概念:栈顶、栈底
栈的基本操作:
进栈(压栈):push
出栈:pop
取栈顶:gettop
文章目录
一、栈的实现
使用一般的列表结构即可实现栈
进栈:li.append
出栈:li.pop
取栈顶:li[-1]
class stack:
def __init__(self):
self.stack=[]
def push(self,element):
self.stack.append(element)
def pop(self):
return self.stack.pop()
def get_top(self):
if len(self.stack)>0:
return self.stack[-1]
else:
return None
def is_empty:
return self.stack
二、栈的应用:括号匹配
给一个字符串,其中包含小括号、中括号、大括号,求该字符串中的括号是否匹配
例如:()()[]{} 匹配,[]( 不匹配
def brace_match(s):
match={'}':'{',']':'[',')':'('}
stack=Stack()
for ch in s:
if ch in {'(','[','{'}:
stack.push(ch)
else:
if stack.is_empty():
return False
elif stack.get_top()==match[ch]:
stack.pop()
else:
return False
if stack.is_empty():
return True
else:
return False