# 用Python实现stack数据结构

用Python实现数据结构 附二进制转10进制算法

class PyStack(object):

def __init__(self,initSize=20,incSize=10):
self.initSize=incSize
self.incSize=incSize
self.stackList=[]
self.top=self.bottom=0

def push(self,ele):
if self.top-self.bottom>=self.initSize:
self.incSize+=self.initSize
self.stackList.append(ele)
self.top+=1

def pop(self):
if self.top-self.bottom>0:
self.top-=1           
     ##ret = self.stackList[self.top]
##self.stackList.remove(ret)      
     ##这两句代码在出栈时会有重大缺陷 remove移除的是第一次出现的位置
     ret=self.stackList.pop()
return ret
else: return None def len(self): return self.top-self.bottomdef showNum(): stack = PyStack() second = input('请输入二进制数:') inputLen = len(second) for c in second: try: num = int(c) except: print('你输入的格式有误except') if num == 1 or num == 0: stack.push(num) else: print('你输入的格式有误not 0 1') break if stack.len() > 0 and inputLen == stack.len(): sumNum = 0 for i in range(stack.len()): sumNum += stack.pop() * (2 ** i) print('二进制数的值是:', sumNum) else: print('input len=%d,stack len=%d' % (inputLen, stack.len()))if __name__=='__main__': showNum()