目录
一、顺序栈
#顺序栈
class SqStack:
def __init__(self): #构造函数
self.data=[] #存放栈中元素,初始为空
def empty(self): #判断栈是否为空
if len(self.data)==0:
return True
return False
def print(self):
print(self.data)
def push(self,e): #元素e进栈
self.data.append(e)
def pop(self): #元素出栈
assert not self.empty()
return self.data.pop()
def gettop(self): #取栈顶元素
assert not self.empty()
#最后一个元素
return self.data[-1]
if __name__ == '__main__':
st=SqStack()
st.push(1)
st.push(2)
st.push(3)
st.push(4)
print("出栈顺序:",end=' ')
while not st.empty():
print(st.pop(),end=' ')
print()
二、链栈
class LinkNode: #单链表结点类
def __init__(self,data=None): #构造方法
self.data=data
self.next=None
class LinkStack: #链栈类
def __init__(self): #构造方法
self.head=LinkNode()
self.head.next=None
def empty(self): #判断栈是否为空
return self.head.next==None
def push(self,e): #元素e进栈
p=LinkNode(e)
p.next=self.head.next
self.head.next=p
def pop(self): #元素出栈
assert self.head.next!=None
p=self.head.next
self.head.next=p.next
return p.data
def gettop(self): #取栈顶元素
assert self.head.next != None
return self.head.next.data
if __name__ == '__main__':
st=LinkStack()
st.push(1)
st.push(2)
st.push(3)
st.push(4)
print("出栈顺序:",end=' ')
while not st.empty():
print(st.pop(),end=' ')
print()
三、中缀转后缀表达式并求解
1.中缀转后缀
这里的SqStack是我们上面的顺序栈(一种的)
from SqStack import SqStack
def postifix_expression(str):
prec={}
prec['*']=3
prec['/']=3
prec['+']=2
prec['-']=2
prec['(']=1
result=[]
mystack=SqStack()
i=0
while i < len(str):
if str[i]>='0' and str[i]<='9':
x=int(str[i])
i+=1
while i<len(str) and str[i]>='0' and str[i]<='9':
x=x*10+int(str[i])
i+=1
result.append(x)
continue
elif str[i]=='(':
mystack.push(str[i])
i+=1
continue
elif str[i]==')':
top=mystack.pop()
while top!='(':
result.append(top)
top=mystack.pop()
i+=1
continue
else:
while (mystack.empty() !=True)and(prec[mystack.gettop()]>prec[str[i]]):
result.append(mystack.pop())
mystack.push(str[i])
i+=1
while not mystack.empty():
result.append(mystack.pop())
return result
2.后缀表达式求解
def calculate(result):
mystack2 = SqStack()
for i in result:
if i=='+'or i=='-'or i=='*' or i=='/':
right=mystack2.pop()
left=mystack2.pop()
if i=='+':
mystack2.push(left+right)
elif i=='-':
mystack2.push(left-right)
elif i=='*':
mystack2.push(left*right)
elif i=='/':
mystack2.push(left/right);
else:
mystack2.push(i)
return mystack2.gettop();
3.测试代码
if __name__ == '__main__':
a1="(56-20)/(4+2)"
b1=postifix_expression(a1)
print(b1)
print(calculate(b1))
a2="12/2*3"
b2 =postifix_expression(a2)
print(b2)
print(calculate(b2))
a3="2*(9+6/3-5)+4"
b3 = postifix_expression(a3)
print(b3)
print(calculate(b3))