00001 #include <cassert> 00002 #include <iostream> 00003 #include "Stack.h" 00004 00005 using std::cout; 00006 00007 // Constructor 00008 Stack::Stack() 00009 { 00010 } 00011 00012 // Destructor needs to deallocate dynamically allocated nodes: 00013 Stack::~Stack() 00014 { 00015 // Remove all dynamic nodes from the list: 00016 Node* iter = head.pnext; 00017 while ( iter != NULL ) { 00018 Node* obsolete = iter; 00019 iter = iter->pnext; 00020 delete obsolete; // remove node from memory 00021 } 00022 } 00023 00024 // Push new element to the stack: 00025 void Stack::push( int value ) 00026 { 00027 head.insert( new Node( value ) ); 00028 } 00029 00030 // Pop element from the stack: 00031 void Stack::pop() 00032 { 00033 assert( !empty() ); 00034 Node* obsolete = head.pnext; 00035 head.remove_next(); 00036 delete obsolete; 00037 } 00038 00039 // Writeable access to element on top of the stack: 00040 int& Stack::top() 00041 { 00042 return head.pnext->data; 00043 } 00044 00045 // Read-only access to element on top of the stack: 00046 int Stack::top() const 00047 { 00048 return head.pnext->data; 00049 } 00050 00051 // Return stack size: 00052 size_t Stack::size() const 00053 { 00054 // minus one accounts for the head node 00055 return head.size() - 1; 00056 } 00057 00058 // Return true if stack is empty 00059 bool Stack::empty() const 00060 { 00061 return head.size() == 1; 00062 } 00063 00064 // Print contents of the stack: 00065 void print_stack( Stack const& st ) 00066 { 00067 if ( st.empty() ) { 00068 cout << "[0] (stack is empty)\n"; 00069 00070 } else { 00071 print_list( *st.head.pnext ); 00072 } 00073 }