Difference between revisions of "Q1sol the solution"

From CDOT Wiki
Jump to: navigation, search
(Created page with ' //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>* n…')
 
Line 1: Line 1:
 
+
<code>
 
//to write a linked list like structure, you must begin with a node.  Without the node,
 
//to write a linked list like structure, you must begin with a node.  Without the node,
 
//you can't have a linked list.
 
//you can't have a linked list.
Line 63: Line 63:
 
   return rc;
 
   return rc;
 
}
 
}
 +
</code>

Revision as of 17:01, 4 August 2010

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

}