實現逆波蘭表達式——棧

想了解棧可以看看這篇文章:
棧的簡單實現——順序棧

逆波蘭表達式

逆波蘭表達式是一種將運算符寫在操作數後面的一種描述方法。

比如:
(1+2)*(3+4) //中綴表達式

寫爲逆波蘭表達式就是:1 2 + 3 4 + *

代碼實現:

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

#define MAX 100

int stack[MAX], top; 

int push(int num){  //入棧 
	
	stack[++top] = num;
}

int pop(){  //出棧 

	return stack[top--]; 
} 
 
int main(){
	char s[10];
	int a, b;
	top = 0;  //棧頂指針初始化
	 
	while(scanf("%s", s) != EOF){
		if(s[0] == '+'){
			a = pop();
			b = pop();
			push(a+b);
		}
		else if(s[0] == '-'){
			a = pop();
			b = pop();
			push(a-b); 
		}
		else if(s[0] == '*'){
			a = pop();
			b = pop();
			push(a*b);
		}
		else{
			push(atoi(s));
		}
	}
	
	printf("%d", pop());
	
	return 0;
} 

結果:

注意:讀入採用 while 語句,利用 scanf 的返回值判斷是否有數據輸入 ,

如果結束輸入,以 ctrl+z 結束輸入
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章