示例#1
0
int main()
{
int x,y,n,result,size;
STACK <char, 10> A;

string expression;

// clear stack
A.Clear();

// get expression from user
cout << "Enter a postfix expression:";
cin >> expression;
size = expression.length();

char item[size];

for(int i=0; i<size; ++i){
	item[i] = expression[i];
}


for(int j=0; j<size; ++j){

	if(item[j] == '+'){
		x = A.Pop();
		y = A.Pop();
		A.Push(y+x);
	}
	else if( item[j] == '*'){
		x = A.Pop();
		y = A.Pop();
		A.Push(y*x);
	}
	else if( item[j] == '/'){
		x = A.Pop();
		y = A.Pop();
		A.Push(y/x);
	}
	else if( item[j] == '-'){
		x = A.Pop();
		y = A.Pop();
		A.Push(y-x);
	}
	else{    
		n = (item[j]) - (48);
		A.Push(n);
	}

}

// output result
result = A.Pop();    
cout << "Result is " << result << endl;

    return(0);
}
示例#2
0
int main()
{
int x,y,n;
STACK <char, 10> A;
char item[10];

// clear stack
A.Clear();

// get expression from user
cout << "Enter a postfix expression with $ at the end: ";
cin.getline(item,10);

// process data
while(strcmp(item, "$") != 0)
{
   if(strcmp(item, "+") == 0)
   {
   	x = A.Pop();
   	y = A.Pop();
   	A.Push(y+x);
   }
   else if(strcmp(item, "*") == 0)
   {
   	x = A.Pop();
   	y = A.Pop();
   	A.Push(y*x);
   }
   else if(strcmp(item, "/") == 0)
   {
   	x = A.Pop();
   	y = A.Pop();
   	A.Push(y/x);
   }
   else if(strcmp(item, "-") == 0)
   {
   	x = A.Pop();
   	y = A.Pop();
   	A.Push(y-x);
   }
   // if its a number
   else
   {    
   	n = atoi(item);
   	A.Push(n);

   }
}

    int r = A.Pop();
    // output result
    cout << "Result is " << r << endl;
    return(0);
}