#ifndef STACK_HPP
#define STACK_HPP
namespace adt{
template<class T>
class stack{
private:
class Node{
public:
T item;
Node* prev;
};
Node* top;
int size;
public:
stack();
~stack();
void empty();
bool isEmpty();
int getSize();
the stack
T* showTop();
T* pop();
void push(const T& newItem);
bool isFull();
};
}
/////////////////////////////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
namespace adt{
template<class T>
stack<T> :: stack(){
top = NULL;
size = 0;
}
template<class T>
stack<T> :: ~stack(){
Node* aux;
while(top){
aux = top;
top = top->prev;
delete aux;
}
}
template<class T>
void stack<T> :: empty(){
Node* aux;
while(top){
aux = top;
top = top->prev;
delete aux;
}
size = 0;
}
template<class T>
bool stack<T> :: isEmpty(){
return top==NULL;
}
template<class T>
int stack<T> :: getSize(){
return size;
}
template<class T>
T* stack<T> :: showTop(){
if(top){
return &(top->item);
}
return NULL;
}
template<class T>
T* stack<T> :: pop(){
if(top){
//save the item
T* pItem = &(top->item);
//save the node to destroy
Node* oldTop = top;
//update the top
top = top->prev;
//destroy the oldTop
delete oldTop;
//update size
size--;
//return the item
return pItem;
}
return NULL;
}
template<class T>
void stack<T> :: push(const T& newItem){
Node* newNode;
try{
newNode = new Node();
}catch( std::bad_alloc &ba ){
throw ba;
}
newNode->prev = top;
newNode->item = newItem;
top = newNode;
size++;
}
template<class T>
bool stack<T> :: isFull(){
Node* newNode;
try{
newNode = new Node();
}catch( std::bad_alloc &ba ){
return true;
}
delete newNode;
return false;
}
}
/////////////////////////////////////////////////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
#include <iostream>
#include "stack.hpp"
using namespace std;
int main(){
adt::stack<float> s;
//testing initial conditions:
cout << "create" << '\n';
cout << "isEmpty: " << s.isEmpty() << "\n";
cout << "getSize: " << s.getSize() << "\n";
cout << "showTop: " << s.showTop() << "\n";
cout << "isFull: " << s.isFull() << "\n\n";
s.push(8.5);
s.push(8.5);
s.push(8.5);
s.push(8.5);
s.push(8.5);
s.push(7.5);
s.push(9.5);
cout << "push" << '\n';
cout << "isEmpty: " << s.isEmpty() << "\n";
cout << "getSize: " << s.getSize() << "\n";
cout << "showTop: " << *(s.showTop()) << "\n";
cout << "isFull: " << s.isFull() << "\n\n";
s.pop();
cout << "pop" << '\n';
cout << "isEmpty: " << s.isEmpty() << "\n";
cout << "getSize: " << s.getSize() << "\n";
cout << "showTop: " << *(s.showTop()) << "\n";
cout << "isFull: " << s.isFull() << "\n";
return 0;
}
PLEASE GIVE A THUMBS UP!!!!!!!!
Get Answers For Free
Most questions answered within 1 hours.