You are on page 1of 2

Stack using Linked List template

# include<iostream>
using namespace std;
template<class t>
class Node
{
private:
t data;//node -data part
Node *next;//pointer to next node
public:
Node *top=NULL;//declare a top pointer
void push(t x)
{
Node *temp;//pointer for temp node
temp=new Node;//creation of new node
if(temp==NULL)
{
cout<<"stack is full";
}
else
{
temp->data=x;//temp node store the value of x
temp->next=top;//temp node pointing to the top node
top=temp;//top pointer storing temp node

}
}
t pop()
{

t x=-1;
if(top==NULL)
{
cout<<"stack is empty";
return x;
}
else
{
Node *t1=top;//declare a new pointer 't'
x=top->data;//x storing the value of top pointer data
top=top->next;//top pointer storing next top address
delete t1;//delete the t1 node
return x;//return the x value
}

}
void display()
{
Node *p=top;
while(p!=NULL)
{
cout<<p->data<<"\t";//print the value
p=p->next;//move the pointer to next node
}
cout<<endl;
}
};
int main()
{
Node<int> n;
n.push(10);
n.push(20);
n.push(30);
cout<<"integer data type"<<endl;
n.display();
cout<<"deleted element="<<n.pop()<<endl;
n.display();
Node<double> n1;
n1.push(10.3);
n1.push(20.6);
n1.push(30.3);
cout<<"double data type"<<endl;
n1.display();
}

You might also like