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