Q1sol the solution

From CDOT Wiki
Revision as of 08:52, 5 August 2010 by Srchandr (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
//to write a linked list like structure, you must begin with a node.  Without the node,
//you can't have a linked list.
template <class T>
struct Node{
  T data_;
  Node<T>* next_;
};

template <class T>
class Stack{
  Node<T>* start_;
public:
  /*this constructor initializes the stack to an empty stack*/
  Stack();
  /*this function adds a piece of data of type T to the stack and returns
    nothing*/
  void push(T data);

  /*removes and returns a piece of data from the stack.  If the stack is
    empty throw the string "empty stack"*/
  T pop()

  /*returns true if empty, false otherwise*/
  bool isempty();
};
template <class T>
Stack<T>::Stack(){
  start_=NULL;
}

template <class T>
void Stack<T>::push(T data){
  Node<T>* nn;
  nn=new Node<T>;
  nn->data_=data;
  nn->next_=start_;
  start_=nn;
}

template <class T>
T Stack<T>::pop(){
  T rc;
  if(isempty()){
    throw "Empty Stack";
  }
  else{  //this else is optional because if you throw an exception,rest
    rc=start_->data_;
    Node<T>* rm=start_;
    start_=start_->next;
    delete rm;
  }
  return rc;

}

template <class T>
bool Stack<T>::isempty(){
  bool rc=true;
  if(start_){
    rc=false;
  }
  return rc;
}