c語言使用棧結構實現字尾表示式計算器(可以實現帶括號的加減乘除簡單計算)
標頭檔案stack.h
#ifndef stack_h
#define stack_h
#include
#include
#define success 1000
#define failure 1001
typedef
struct
node;
typedef
struct
stack;
intinitstack
(stack *stack)
;int
push
(stack *s,
int num)
;int
gettop
(stack *s)
;int
pop(stack *s)
;int
emptystack
(stack *s)
;#endif
stack.c
#include
"stack.h"
intinitstack
(stack *s)
s->top =
null
; s->length =0;
//空棧
return success;
}int
push
(stack *s,
int num)
node *n =
malloc
(sizeof
(node));
if(null
== n)
n->data = num;
n->next = s->top;
s->top = n;
//更新棧頂指標
s->length++
;return success;
}int
gettop
(stack *s)
if(s->top ==
null
)return s->top->data;
}int
pop(stack *s)
if(s->top ==
null
)//空棧不能出棧
node *n = s->top;
int data = n->data;
s->top = n->next;
free
(n);
s->length--
;return data;
}int
emptystack
(stack *s)
return
(s->top ==
null
)? success : failure;
}
main.c
#include
"stack.h"
intpriority
(char ch)
}int
main()
char opt[
128]=;
int i =
0, tmp =
0, num1, num2;
printf
("please enter an expression:\n");
scanf
("%s"
, opt)
;while
(opt[i]
!='\0'
||emptystack
(&s_opt)
!= success)
//表示式不為空或棧不為空就繼續
}else
//操作符
elseif(
gettop
(&s_opt)
=='('
&& opt[i]
==')'
)else}}
}}printf
("the result is:%d\n"
,gettop
(&s_num));
return0;
}
棧與字尾表示式C實現
1 include2 include3 4 typedef char datatype 5 typedef struct stack 6stack 1112 初始化空棧 13 void initstack stack st,int sz 14 19 釋放站空間 20 void freestack s...
棧結構之後綴表示式
棧採用順序棧儲存,試設計演算法實現將表示式轉換成字尾表示式輸出。例如,輸入表示式 a b c d e f g 輸出其字尾表示式 abc de f g include include define true 1 define false 0 define ok 1 define error 0 def...
字尾表示式 棧
若干行,每行對應乙個中綴表示式 若干行,每行對應乙個由中綴表示式轉換而來的字尾表示式 x a y b z f a b c d m n s t y a b c d e f gxayb zf abc dm n st y abc def g 解題思路 首先如何實現中綴表示式轉換成字尾表示式,方法如下 1....