該程序應該採用後綴算術表達式,然後編譯該表達式的值..每次讀取整數時,它將被推入堆棧中。否則,兩個整數將是如果讀取了+, - ,*,則彈出。調用堆棧打印函數時無限循環
class Stack {
Node *head;
public:
Stack() {
head = NULL;
};
void push(int data);
int pop();
bool isEmpty();
void print();
};
void Stack::push(int data)
{
Node * temp = new Node(data);
temp->next = head;
head = temp;
delete temp;
}
int Stack::pop()
{
int x = head->data;
head = head->next;
return x;
}
bool Stack::isEmpty(){
return head == NULL;
}
void Stack::print(){
Node * temp = head;
while (temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
delete temp;
}
int main() {
Stack st;
char exp [] = "23+", c;
int i, a;
for (i = 0; exp[i] != '\0'; i++){
c = exp[i];
if (c == '+'&&!st.isEmpty()){
a = st.pop() + st.pop();
st.push(a);
}
else if (c == '-'&&!st.isEmpty()){
a = st.pop() - st.pop();
st.push(a);
}
else if (c == '/'&&!st.isEmpty()){
a = st.pop()/st.pop();
st.push(a);
}
else if (c == '*'&&!st.isEmpty()){
a = st.pop() * st.pop();
st.push(a);
}
else if (c == '0')
st.push(0);
else if (c == '1')
st.push(1);
else if (c == '2')
st.push(2);
else if (c == '3')
st.push(3);
else if (c == '4')
st.push(4);
else if (c == '5')
st.push(5);
else if (c == '6')
st.push(6);
else if (c == '7')
st.push(7);
else if (c == '8')
st.push(8);
else if (c == '9')
st.push(9);
cout << c << endl;
st.print();
}
cin >> a;
return 0;
}
當我打電話主打印功能,我得到一個無限循環作爲輸出.. 我試圖尋找這是造成一個無限循環的事情,但我找不到它。
爲什麼你'刪除臨時;'當它等於NULL的'堆棧:: print'方法? – SHR 2015-02-23 22:00:59
更好的問題:你爲什麼要在你的**'Stack :: push' **函數中刪除temp;'那根本不應該在那裏。 – WhozCraig 2015-02-23 22:03:17
與Java不同,C++沒有垃圾收集器。如果我沒有刪除它,我會失去內存。delete temp;是在循環之外..我不認爲它會導致無限循環。 – Raghad 2015-02-23 22:03:39