-
C++ (
http://www.daniweb.com/forums/forum8.html)
| cessna172 | Feb 22nd, 2008 6:10 pm | |
| Dynamic stack in c++ NODE *head;
public:
void push(int value){
NODE *temp = (NODE*) new NODE;
temp->value = value;
temp->link = head;
head = temp;
}//end of push.
void pop(int&value) {
NODE *temp = head;
value = head->value;
head = head->link;
delete temp;
}//end of pop.
int is_empty(void){
return head == NULL;
}//end of is_empty.
STACK (void) {head = NULL;}
~STACK(){
int value;
while(!is_empty()) pop(value);
}//end of destructor.
};//end of STACK.
int main(void) {
STACK S;
int value;
S.push(5);
S.push(10);
S.push(15);
for(int i=0; i<3; i++){
S.pop(value);
cout<<"Popped: "<<value<<endl;
}//end of for.
return(0);
}//end of main.
Can anyone please tell me briefly what this program actually does and how it works? |
| Dave Sinkula | Feb 22nd, 2008 7:26 pm | |
| Re: Dynamic stack in c++ Have you ever heard of "debugging with printf"? A similar thing can be done with cout as well. You pepper this code with statements that display for you any items of interest while the program is running. It's a good way to see for yourself what is going on in code. |
| SpS | Feb 22nd, 2008 11:24 pm | |
| Re: Dynamic stack in c++ Why are you taking pain by handling memory yourself. Use power of STL.
#include <vector>
#include <stdexcept>
template <typename T>
class Stack
{
private:
std::vector<T> elems; // elements
public:
void push(T const&); // push element
void pop(); // pop element
T top() const; // return top element
bool empty() const // return whether the stack is empty
{
return elems.empty();
}
};
template <typename T>
void Stack<T>::push (T const& elem)
{
elems.push_back(elem); // append copy of passed elem
}
template<typename T>
void Stack<T>::pop ()
{
if (elems.empty())
{
throw std::out_of_range("Stack<>::pop(): empty stack");
}
elems.pop_back(); // remove last element
}
template <typename T>
T Stack<T>::top () const
{
if (elems.empty())
{
throw std::out_of_range("Stack<>::top(): empty stack");
}
return elems.back(); // return copy of last element
} |
| All times are GMT -4. The time now is 5:18 am. | |
Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC