Posted on 2012-09-17 13:06
hoshelly 閱讀(254)
評論(0) 編輯 收藏 引用 所屬分類:
DS && Algorithm
#include<stdio.h>
#include<
string.h>
#include<stdlib.h>
#define M 1000
static int N;
//N棧的大小
static int *s;
void STACKinit(
int maxN)
//建立一個動態數組s,相當于建立并初始化棧
{
s = (
int *)malloc(maxN*
sizeof(
int));
N=0;
}
int STACKempty()
{
return N==0;
}
void STACKpush(
int item)
{
s[N++] = item;
}
int STACKpop()
{
return s[--N];
}
int main()
//程序作用:將中綴表達式轉為后綴表達式
{
char a[M];
gets(a);
//輸入中綴表達式
STACKinit(N);
int i,len=strlen(a);
for(i=0;i<len;i++)
{
if(a[i] == ')')
printf("%c ",STACKpop());
//遇到右括號彈出棧頂的運算符
if((a[i] == '+') || (a[i] == '*'))
STACKpush(a[i]);
//將運算符壓入棧
if((a[i] == '-') || (a[i] =='/'))
STACKpush(a[i]);
if((a[i] >= '0') && (a[i] <= '9'))
//遇到數字則輸出
printf("%c ",a[i]);
}
return 0;
}
示例:
