Stack Using Linked List In Data Structure Using C++

Data Structure Using C++

Stack Data Structure

Stack Using Linked List

class stack
{
 private:
  node *head;
 public:
  stack();
  void push(int val);
  int pop ();
  int top();
  int isEmpty ();
};
stack::stack()
{
 head=NULL;
}
void stack::push(int val)
{
 node *ptr= new node (val);
 ptr->setNext(head);
 head=ptr;
}
int stack::pop()
{
 if(isEmpty())
 {
  cout<<"Error: Stack is empty. can't pop element."<<endl;
 }
 else
 {
  int val=head->get();
  head=head->getNext();
  return val;
 }
}
int stack::top()
{
 return head->get();
}
int stack::isEmpty()
{
 return head==NULL;
}
int main ()
{
 int op1, op2;
 stack s;
 s.pop();
 s.push(3);
 s.push(5);
 s.push(7);
 cout<<"Popped element is : "<<s.pop()<<endl;
 cout<<"top element is : "<<s.top()<<endl;
}

Let me know in the comment section if you have any question.

Previous Post:
Stack Using Array In Data Structure Using C++

Comments