- #include<stdio.h>
- #include<string.h>
- #include<ctype.h>
- #include<stdlib.h>
- #define MAXSIZE 30
- typedef int ElemType;
- typedef struct Stack{//棧結構
- ElemType data[MAXSIZE];
- int top;//棧頂指針
- }Stack,*pStack;
- void initStack(pStack S){//初始化棧
- S->top = -1;
- }
- bool push(pStack S,ElemType e){
- if(S->top == MAXSIZE-1){
- puts("棧滿");
- return false;
- }
- S->data[++(S->top)] = e;
- return true;
- }
- bool pop(pStack S,ElemType *e){
- if(S->top == -1){
- puts("棧空");
- return false;
- }
- *e = S->data[(S->top)--];
- return true;
- }
- int main(void){
- char string[MAXSIZE];//存儲字符串
- char tempNumber[MAXSIZE];//存儲數值字符
- char ch;//分解每個字符
- int index;
- int number;//從字符中獲得的數值
- int result = 0;//最終結果
- int count = 0;//數字計數
- int a1,a2;//輔助數值計算
- bool tag;//標誌位,數字是否已經結束
- Stack numberStack;//數字棧
- pStack S = &numberStack;//指向棧的指針
- initStack(S);//初始化棧
- puts("Enter a string");
- gets(string);
- for(index=0;index<strlen(string);index++){
- ch = string[index];
- if(isdigit(ch)){
- tag = true;//現在輸入的是數字
- tempNumber[count] = ch;
- count++;
- }
- else{
- if(tag){//判斷上一個字符是不是數值
- tempNumber[count] = '\0';//一個數值結束了
- number = atoi(tempNumber);
- push(S,number);
- count = 0;//重新計算數值
- tag = false;
- }
- switch(ch){
- case '+':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1+a2);
- break;
- case '-':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1-a2);
- break;
- case '*':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1*a2);
- break;
- case '/':
- pop(S,&a2);
- pop(S,&a1);
- push(S,a1/a2);
- break;
- default:
- break;
- }
- }
- }
- pop(S,&result);
- printf("%d",result);
- getchar();
- return 0;
- }