所以我正在评估Postfix
表达式使用堆栈。表达式10 6 -
的读数为10 - 6
中缀,应该等于4
。但它不,它等于-4
。更糟的是,即使我尝试反转代码,它仍然等于-4
。我不确定这是否是我的堆栈或函数调用错误,或者C++的一些怪癖。但是,如果我将一个弹出的值从堆栈中存储到一个变量中,然后执行该等式,则可以正常工作。Postfix负面是不正确和通信
相关代码: Stack类
template <class Item>
class stack {
private:
struct node {
Item item;
node* next;
node(Item x, node* t) {
item = x;
next = t;
}
};
typedef node* link;
link head;
public:
stack(int) { head = 0; }
int empty() const { return head == 0; }
void push(Item x) { head = new node(x, head); }
Item pop() {
Item v = head->item;
link t = head->next;
delete head;
head = t;
return v;
}
};
Evalutating the negative operation
else if (argv[i][0] == '-') {
stck.push(((-1) * stck.pop()) + stck.pop()); // A-B = -B+A
// stck.push(stck.pop()+((-1)*stck.pop())); //A-B = -B+A
} // Both equations equal the same thing (Note I dont use both at the same
// time)
这工作
int n = (stck.pop());
stck.push(-1*n+stck.pop()); //A-B = -B+A
'pop' return和'Item',Item的'operator *'的实现是什么,至少是?它更好[MCVE](http://stackoverflow.com/help/mcve) – NetVipeC 2014-09-24 16:18:51