码迷,mamicode.com
首页 > 编程语言 > 详细

C语言实现中缀表达式转后缀表达式

时间:2017-06-24 22:41:20      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:pre   turn   span   struct   char   src   can   stack   bsp   

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define STACK_INIT_SIZE 20
#define STACKINCREMENT  10

typedef char ElemType;
typedef struct {
    ElemType *base;
    ElemType *top;
    int StackSize;
}sqStack;
void InitStack(sqStack *s){
    s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if( !s->base ){
        exit(0);
    }
    s->top = s->base;
    s->StackSize = STACK_INIT_SIZE;
}
void push(sqStack *s,ElemType e) {
    if( s->top - s->base >= s->StackSize){
        s->base = (ElemType *)realloc(s->base,(s->StackSize+STACKINCREMENT)*sizeof(ElemType));
        if( !s->base ){
            exit(0);
        }
    }
    *(s->top) = e;
    s->top++;
}
void pop(sqStack *s,ElemType *e){
    if( s->top == s->base){
        return;
    }
    *e = *--(s->top);
}
int Stacklen(sqStack s){
    return (s.top-s.base);
}
int main()
{
    sqStack s;
    char c, e;

    InitStack(&s);

    printf("请输入中缀表达式,以#作为结束标志:");
    scanf("%c",&c);

    while( c != # ){
        while ( c>=0 && c<=9 ){
            printf("%c",c);
            scanf("%c",&c);
            if (c<0||c>9){
                printf(" ");
            }
        }
        if ( ) == c )
        {
            pop(&s, &e);
            while( ( != e )
            {
                printf("%c ",e);
                pop(&s,&e);
            }
        }
        else if ( +==c || -==c)
        {
            if ( !Stacklen(s) )
            {
                push(&s,c);
            }
            else
            {
                do
                {
                    pop(&s,&e);
                    if ( (==e )
                    {
                        push(&s,e);
                    }
                    else{
                        printf("%c ",e);
                    }
                }while( Stacklen(s) && (!=e );
                push(&s,c);
            }
        }
        else if ( *==c || /==c || (==c )
        {
            push(&s,c);
        }
        else if (#==c) {
            break;
        }
        else{
            printf("出错,输入格式错误\n");
            return -1;
        }
        scanf("%c",&c);
    }
    while( Stacklen(s) ){
        pop(&s,&e);
        printf("%c ",e);
    }
    return 0;
}

运行结果:

技术分享

 

C语言实现中缀表达式转后缀表达式

标签:pre   turn   span   struct   char   src   can   stack   bsp   

原文地址:http://www.cnblogs.com/ncuhwxiong/p/7074632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!