标签:
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 #define OK 1
5 #define ERROR 0
6 #define STACK_INIT_SIZE 20
7 #define STACK_INCREMENT 10
8
9 typedef char Elemtype;
10 typedef int Status;
11
12 typedef struct StackNode{
13 Elemtype* base;
14 Elemtype* top;
15 int stackSize;
16 }StackNode;
17 typedef struct StackNode* Stack;
18
19 Status InitStack(Stack s){
20 s->base = (Elemtype*)malloc(sizeof(Elemtype) * STACK_INCREMENT);
21 if(! s->base){
22 return ERROR;
23 }
24 s->top = s->base;
25 s->stackSize = STACK_INIT_SIZE;
26 return OK;
27 }
28 Status Pop(Stack s,Elemtype* value){
29 if(s->base == s->top){
30 printf("pop ERROR\n");
31 return ERROR;
32 }
33 *value = *(--(s->top));
34 return OK;
35 }
36 Status Push(Stack s, Elemtype value){
37 if(s->top - s->base == s->stackSize){
38 s->base = (Elemtype*)realloc(s->base,sizeof(Elemtype) * (STACK_INIT_SIZE + STACK_INCREMENT));
39 if(! s->base)
40 return ERROR;
41 s->top = s->base + STACK_INIT_SIZE;
42 s->stackSize = STACK_INCREMENT + STACK_INIT_SIZE;
43 }
44 *(s->top) = value;
45 s->top++;
46 return OK;
47 }
48 int StackLength(Stack s){
49 return s->top - s->base;
50 }
51 //test
52 Status ShowStack(Stack s){
53 while(s->top != s->base){
54 printf("%c ",*(--(s->top)));
55 }
56 printf("\n");
57 }
58
59 Status Infix2Postfix(){ //将中缀表达式转化为后缀表达式
60 StackNode s;
61 InitStack(&s);
62 char c;
63 char c1;
64 printf(" Please Enter Infix expression\n");
65 printf(" -------note: number separeted by space,end of ‘#‘\n\n");
66 scanf("%c", &c);
67 /* Note:如果是数字: 直接输出控制台;
68 * 如果是*,/,(: 直接Push
69 * 如果是+,-: 则要将*,/,+,-都进行Pop,直到stack为空或者是遇到了‘(‘
70 * 如果是‘)‘: 将在遇到‘(‘之前的所有的都要Pop
71 * */
72 while(‘#‘ != c){
73 while(c >= ‘0‘ && c <= ‘9‘){ //如果是数字,则直接输出
74 printf("%c", c);
75 scanf("%c", &c);
76 if( c < ‘0‘ || c > ‘9‘){
77 printf("%c", ‘ ‘);
78 break;
79 }
80 }
81 if(‘+‘ == c || ‘-‘ == c){ //如果是 + 或者是 -
82 if(!StackLength(&s)){ //如果stack为空的话,直接Push
83 Push(&s,c);
84 }
85 else{ //不为空的话需要Pop进行比较/+-*都需要Pop
86 Pop(&s,&c1);
87 while( ‘(‘ != c1 ){
88 printf("%c ", c1);
89 if(StackLength(&s) == 0){
90 break;
91 }
92 else
93 Pop(&s, &c1);
94 }
95 if( ‘(‘ == c1 )
96 Push(&s, c1);
97 Push(&s, c);
98 }
99 }
100 else if(‘*‘ == c || ‘/‘ == c || ‘(‘ == c){ //如果是*或者是/
101 Push(&s, c);
102 }
103 else if( ‘)‘ == c ){
104 Pop(&s,&c1);
105 while( ‘(‘ != c1){
106 printf("%c ", c1);
107 Pop(&s, &c1);
108 }
109 }
110 else if( ‘#‘ == c ){
111 break;
112 }
113 else{
114 printf("Input Is ERROR!\n");
115 return ERROR;
116 }
117 scanf("%c", &c);
118 }
119
120 while(StackLength(&s)){
121 Pop(&s,&c1);
122 printf("%c ", c1);
123 }
124 return OK;
125 }
126 int main(){
127 Infix2Postfix();
128 /*
129 Stack s;
130 InitStack(s);
131 Push(s,‘a‘);
132 Push(s,‘r‘);
133 Push(s,‘e‘);
134 Push(s,‘d‘);
135 ShowStack(s);
136 */
137 return 0;
138 }
标签:
原文地址:http://www.cnblogs.com/robin-xu/p/5224379.html