【Python】【数据结构】【栈的实现】【中缀转后缀表达式并求解】

目录

一、顺序栈

二、链栈

三、中缀转后缀表达式并求解 

1.中缀转后缀

2.后缀表达式求解

3.测试代码


一、顺序栈

#顺序栈
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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

桜キャンドル淵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值