栈的实现:
# 定义一个栈类
class Stack():
# 栈的初始化
def __init__(self):
self.items = []
# 判断栈是否为空,为空返回True
def isEmpty(self):
return self.items ==[]
# 向栈内压入一个元素
def push(self, item):
self.items.append(item)
# 从栈内推出最后一个元素
def pop(self):
return self.items.pop()
# 返回栈顶元素
def peek(self):
return self.items[len(self.items)-1]
# 判断栈的大小
def size(self):
return len(self.items)
字符串反转:
#字符串反转
def revstring(str):
s = Stack()
outputstr = '' for i in str:
s.push(i)
while not s.isEmpty():
outputstr += s.pop() return outputstr
括号匹配:
#括号匹配
def parCheker(str):
s = Stack()
balanced = True
index = 0
while index<len(str) and balanced:
str1 = str[index]
if str1 in '([{':
s.push(str1)
else:
if s.isEmpty():
balanced = False
else:
top = s.pop()
if not matches(top,str1):
balanced = False index += 1 if s.isEmpty() and balanced:
return True
else:
return False def matches(open,close):
opens = '([{'
closes = ')]}'
return opens.index(open) == closes.index(close)
十进制转换成二进制:
#十进制转换为二进制
def Dec2Bin(num):
s = Stack()
while num>0:
temp = num%2
s.push(temp)
num = num // 2 binString = ''
while not s.isEmpty():
binString += str(s.pop()) return binString
参考:https://github.com/Jack-Lee-Hiter/AlgorithmsByPython/blob/master/Stack.py