栈-中缀式转后缀式

#include "stdafx.h"
#include "malloc.h"
#include "windows.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define INIT_SIZE   20
#define INCRESEMENT 10
#define MAXBUFFER   10  
typedef char ElemType;
typedef struct
{
    int stacksize;
    ElemType *base;
    ElemType *top;
}sqStack;

void initStack(sqStack *s)
{
    s->base = (ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
    if(!s->base) exit(0);
    s->top = s->base;
    s->stacksize = INIT_SIZE;
}

void Push(sqStack *s, ElemType e)
{
    if(s->top - s->base >= s->stacksize)
    {
        s->base = (ElemType*)realloc(s->base, (s->stacksize+INCRESEMENT)*sizeof(ElemType));
        if(!s->base) exit(0);
    }
    *(s->top) = e;
    s->top++;
}

void Pop(sqStack*s, ElemType *e)
{
    if(s->base == s->top) return;
    s->top--;
    *e = *(s->top);
}

int StackLen(sqStack s)
{
    return (s.top-s.base);
}

int Priority(sqStack s)
{
    if(s.base == s.top) return 0;
    else
    {
        s.top--;
        switch(*s.top)
        {
        case '+':
        case '-': 
            return 1;
        case '*':
        case '/': 
            return 2;
        case '(': 
            return -1;
        }
    }
}

int decidec( ElemType e)
{
    if(isdigit(e) || e=='.') return 0;
    if(e=='*' || e=='/' || e=='(') return 1;
    if(e==')') return 2;
    else return 3;
}

int main(int argc, char* argv[])
{
    sqStack s;
    initStack(&s);
    printf("输入中缀式(#结束):\n");
    char c;
    scanf("%c",&c);
    char str[MAXBUFFER];
    ElemType x;
    int i = 0;
    while(c!='#')
    {
        switch(decidec(c))
        {
        case 0:
            while(!decidec(c))
            {
                printf("%c",c);
                scanf("%c",&c);
            }
            printf(" ");
            break;
        case 1:
            Push(&s, c);
            scanf("%c",&c);
            break;
        case 2:
            while(StackLen(s)){
                    Pop(&s, &x);
                    if(x=='(') break;
                    else printf("%c ",x);
                }
            scanf("%c",&c);
            break;
        case 3:
            if(Priority(s)==2)
            {
                while(StackLen(s)){
                    Pop(&s, &x);
                    if(x=='(') break;
                    else printf("%c ",x);
                }
            }
            else Push(&s,c);
            scanf("%c",&c);
            break;
        }
    }
    while(StackLen(s))
    {
        Pop(&s, &x);
        printf("%c ",x);
    }
    printf("\n");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值