数据结构实验之栈与队列二:一般算术表达式转换成后缀式

来源:互联网 发布:黑色沙漠捏脸数据下载 编辑:程序博客网 时间:2024/06/07 03:32

学会栈的使用(链表构造)(创建,入栈,出栈,置空,判空判满)

#include <iostream>#include <stdio.h>#include <malloc.h>using namespace std;typedef char ElemType;typedef struct SNode{    ElemType Data;    struct SNode *Next;}*Stack;//置空栈void MakeEmpty(Stack PtrS){    PtrS->Next = NULL;}//创建栈Stack CreatStack(){    Stack PtrS;    PtrS = (Stack)malloc(sizeof(struct SNode));    if(PtrS == NULL)        exit(-1);    MakeEmpty(PtrS);    return PtrS;}//判空int IsEmpty(Stack PtrS){    return PtrS->Next == NULL;}//入栈void Push(ElemType X, Stack PtrS){    Stack p;    p = (Stack)malloc(sizeof(SNode));    p->Data = X;    p->Next = PtrS->Next;    PtrS->Next = p;}//出栈(弹出栈顶元素)ElemType Pop(Stack PtrS){    if(!IsEmpty(PtrS))    {        ElemType Topc;        Stack FirstCell = PtrS->Next;        PtrS->Next = FirstCell->Next;        Topc = FirstCell->Data;        free(FirstCell);        return Topc;    }    else        exit(-1);}//返回栈顶元素ElemType Top(Stack PtrS){    if(!IsEmpty(PtrS))        return PtrS->Next->Data;    else        return 0;}void Trans(ElemType c, Stack PtrS){    if(c>=97 && c<=122)    {        cout<<c;        return ;    }    else    {        if(c == '(')            Push(c, PtrS);        else if(c == ')')        {            while(Top(PtrS) != '(')                cout<<Pop(PtrS);            Pop(PtrS);        }        else if(c=='*' || c=='/')        {            if(IsEmpty(PtrS))            {                Push(c, PtrS);                return ;            }            if(Top(PtrS)=='+'||Top(PtrS)=='-'||Top(PtrS)=='(')                Push(c, PtrS);            else            {                while(!IsEmpty(PtrS)||Top(PtrS)!='*'||Top(PtrS)!='/')                    cout<<Pop(PtrS);                Push(c, PtrS);            }        }        else if(c=='+' || c=='-')        {            if(IsEmpty(PtrS)||Top(PtrS)=='(')            {                Push(c, PtrS);                return ;            }            else            {                while(!IsEmpty(PtrS)&&Top(PtrS)!='(')                    cout<<Pop(PtrS);                Push(c, PtrS);            }        }    }}int main(){    Stack PtrS;    PtrS = CreatStack();    ElemType c[100];    gets(c);    for(int i=0; c[i]!='#'; i++)    {        Trans(c[i], PtrS);    }    while(!IsEmpty(PtrS))    {        cout<<Pop(PtrS);    }    return 0;}
阅读全文
0 0