码迷,mamicode.com
首页 > 其他好文 > 详细

中缀 转 后缀

时间:2015-11-24 22:53:23      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:

#include <cstdio>
#include <cstdlib>
//#define _OJ_
#define maxsize 100
typedef struct stack1
{
    char *elem;
    int top;
    int base;
} stack1, *stack;


stack
creat_stack(void)
{
    stack s;
    s = (stack) malloc (sizeof(stack1));
    s->elem = (char*) malloc (maxsize * sizeof(char));
    s->top = s->base = 0;
    return s;
}

char
pop(stack s)
{
    return s->elem[--s->top];
}

void
push(stack s, char ch)
{
    s->elem[s->top++] = ch;
}

int
isempty(stack s)
{
    if(s->top == s->base)
        return 1;
    else
        return 0;
}

char
gettop(stack s)
{
    return s->elem[s->top - 1];
}

int
getrank(char ch)
{
    switch (ch) {
    case ‘+‘:
    case ‘-‘:return 1;break;
    case ‘*‘:
    case ‘/‘:return 2;break;
    case ‘(‘:return 3;break;
    default :return 100;
    }
}


int main(int argc, char const *argv[]) {
#ifndef _OJ_  //ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif
    char ch1;
    int n1, n2;
    int i = 0;
    stack s;
    char  str[100];


    while (scanf("%s", str) != EOF) {
    if(str[1] == ‘\0‘)    continue;
    s = creat_stack();
    i = 0;
    while (str[i] != ‘\0‘) {
      if(‘0‘ <= str[i] && str[i] <= ‘9‘)
        printf("%c", str[i]);

      else if(str[i] == ‘(‘)
        push(s,str[i]);

        else if(str[i] == ‘)‘)
            {
            while(gettop(s) != ‘(‘)
            printf("%c", pop(s));
            pop(s);
            }
        else
        {
         if(isempty(s))    push(s,str[i]);
         else{
         ch1 = gettop(s);//printf("ch1 == %c\n", ch1);
         n1  = getrank(str[i]);//printf("n1 == %d\n", n1);
         n2  = getrank(ch1);//printf("n2 == %d\n", n2);
         while((ch1 != ‘(‘) && (isempty(s) != 1) && (n1 <= n2)) {
            printf("%c", pop(s));    if(isempty(s))    break;
            ch1 = gettop(s);
            n2  = getrank(ch1);
        }
        push(s,str[i]);
        }
         // printf("top == %c\n", gettop(s));
        //printf("rank == %d\n", getrank(str[i]));
        //printf("%c\n", str[i]);
        }

        i++;
    }


    while (!isempty(s))
      printf("%c", pop(s));
      printf("\n");

}

    return 0;
}


/*12+
12+3*45*+*/

中缀 转 后缀

标签:

原文地址:http://www.cnblogs.com/airfand/p/4993173.html

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