lundi 23 février 2015

Infinite loop when calling the stack print function


This program should takes a postfix arithmetic expression then compiles the values of that expression.. Each time an integer is read, its gonna get pushed into the stack.. Otherwise, Two integers would be popped if +,-,* is read.





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;

}



When I call the print function in main, I get an infinite loop as an output.. I tried looking for the thing that's causing an infinite loop but I couldn't find it.




Aucun commentaire:

Enregistrer un commentaire