#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; } |
Description :
This is the one stop educational site for all Electronic and Computer students. If you want to learn something new then we are here to help. We work on Microcontroller projects, Basic Electronics, Digital electronics, Computer projects and also in basic c/c++ programs.
#Home #Sitemap #Resources #Terms of Use
Copyright©2012 electrofriends.com All Rights Reserved
Contact:[email protected]
GOOD WORK.