C++ program to implement stack using Linked List

#include <iostream.h>
template<class T>
class Node
{
friend LinkedStack<T>;
private:
T data;
Node<T> *link;
};
template<class T>
class LinkedStack {
public:
LinkedStack() {top = 0;}
~LinkedStack();
int IsEmpty() const {return top == 0;}
T Top() const;
LinkedStack<T>& Add(const T& x);
LinkedStack<T>& Delete(T& x);
private:
Node<T> *top; 
};
template<class T>
LinkedStack<T>::~LinkedStack()
{// Stack destructor..
Node<T> *next;
while (top) {
next = top->link;
delete top;
top = next;
}
}
template<class T>
T LinkedStack<T>::Top() const
{// Return top element.
if (IsEmpty()) cout<<"Stack empty:";
else
return top->data;
}
template<class T>
LinkedStack<T>& LinkedStack<T>::Add(const T& x)
{// Add x to stack.
Node<T> *p = new Node<T>;
p->data = x;
p->link = top;
top = p;
return *this;
}
template<class T>
LinkedStack<T>& LinkedStack<T>::Delete(T& x)
{// Delete top element and put it in x.
if (IsEmpty()) 
{
cout<<"Stack empty";
return *this;
}
x = top->data;
Node<T> *p = top;
top = top->link;
delete p;
return *this;
}
void main(void)
{
int x;
LinkedStack<int> S;
S.Add(1).Add(2).Add(3).Add(4);
cout << "Stack should be 1234" << endl;
cout << "Stack top is " << S.Top() << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
S.Delete(x);
cout << "Deleted " << x << endl;
}
Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in