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;
}

One Response to “C++ program to implement stack using Linked List”

Leave a Reply