on the same line of our previous post, here is how to write Stack in c++:
//stack program
#include <iostream.h>
struct node
{
int data;
node *link;
};
class stack
{
private:
node *top;
public:
stack()
{
top = NULL;
}
void push(int item)
{
node *temp;
temp = new node;
if(temp == NULL)
cout << endl << "Stack is full";
temp->data = item;
temp->link = top;
top = temp;
}
int pop()
{
if(top == NULL)
{
cout << endl << "Stack is empty";
return NULL;
}
node *temp;
int item;
temp = top;
item = temp->data;
top = top->link;
delete temp;
return item;
}
~stack()
{
if(top == NULL)
return;
node *temp;
while(top != NULL)
{
temp = top;
top = top->link;
delete temp;
}
}
};//end class stack
void main()
{
stack a;
s.push(4);
s.push(26);
s.push(12);
s.push(7);
s.push(19);
s.push(90);
int i = s.pop();
cout << endl << "Item popped = " << i;
i = s.pop();
cout << endl << "Item popped = " << i;
i = s.pop();
cout << endl << "Item popped = " << i;
}