我一直在运行它并输入“12+”作为表达式。当它进入 while 循环时,它会卡住,就好像条件从未满足一样。我不明白为什么这是因为在 while 循环之前“它”等于 2,所以甚至不应该使用循环。
//array based stack implementation
class Stack
{
private:
int capacity; //max size of stack
int top; //index for top element
char *listArray; //array holding stack elements
public:
Stack (int size = 50){ //constructor
capacity = size;
top = 0;
listArray = new char[size];
}
~Stack() { delete [] listArray; } //destructor
void push(char it) { //Put "it" on stack
listArray[top++] = it;
}
char pop() { //pop top element
return listArray [--top];
}
char& topValue() const { //return top element
return listArray[top-1];
}
char& nextValue() const {//return second to top element
return listArray[top-2];
}
int length() const { return top; } //return length
};
int main()
{
string exp;
char it = ' ';
int count;
int push_length;
cout << "Enter an expression in postfix notation:\n";
cin >> exp;
cout << "The number of characters in your expression is " << exp.length() << ".\n";
Stack STK;
for(count= 0; count < exp.length() ;count++)
{
if (exp[count] == '+')
{
it = exp[count - 1];
cout << it << "\n";
while (it != 1 || it != 2 || it != 3 || it != 4 || it != 5 || it != 6 || it != 7 || it != 8 || it != 9 || it != 0)
{
cout << it << "\n";
it = exp[count--];
}
STK.push(it);
//cout << STK.topValue() << "\n";
it = exp[count --];
if (it == 1 || it == 2 || it == 3 || it == 4 || it == 5 || it == 6 || it == 7 || it == 8 || it == 9 || it == 0){
STK.push(it);
cout << it;
}
cout << STK.topValue() << "\n";
it = STK.topValue() + STK.nextValue();
STK.pop();
STK.pop();
STK.push(it);
cout << STK.topValue() << "\n";
}
}
cout << "The number of characters pushed into the stack is " << STK.length() << ".\n";
push_length = STK.length();
return(0);
}