Please feel free to be as harsh as possible.
Implementation file:
#include "Stack.h"
#include <iostream>
using namespace std;
// Initializes an empty Stack.
Stack::Stack() {
this->head = new node();
this->num_elements = 0;
// set default values for head
this->head->next = 0;
this->head->value = 0;
}
// Cleans up memory before the Stack's destruction.
Stack::~Stack() {
while (this->head->next != 0) {
pop();
}
delete this->head;
}
// Pushes value onto the top of the stack.
void Stack::push(int value) {
node* newTopNode = new node();
newTopNode->value = value;
// currentTopNode may be null if stack is empty
node* currentTopNode = this->head->next;
this->head->next = newTopNode;
newTopNode->next = currentTopNode;
this->num_elements++;
}
// Pops the top-most value off the stack and returns its value.
int Stack::pop() {
if (this->head->next == NULL) {
cout << "\nIllegal State Exception: You cannot pop an empty stack." << endl;
return 0;
} else {
node* topNodeToRemove = this->head->next;
// save the value of the node before deleting it
int topNodeValue = topNodeToRemove->value;
this->head->next = this->head->next->next;
delete topNodeToRemove;
this->num_elements--;
return topNodeValue;
}
}
// Returns the value at the top of the stack. Works similarly to pop(), but
// retains the internal structure of the stack. That is, it does not remove
// the top-most element.
int Stack::getTopElement() const {
if (this->head->next == NULL) {
cout << "\nIllegal State Exception: You cannot get the top element of an empty stack." << endl;
return 0;
} else {
return this->head->next->value;
}
}
// Returns the number of elements currently in the stack.
int Stack::size() const {
return this->num_elements;
}
Header file:
#ifndef STACK_H_
#define STACK_H_
class Stack {
public:
Stack();
~Stack();
void push(int);
int pop();
int getTopElement() const;
int size() const;
private:
struct node {
int value;
node* next;
};
node* head;
int num_elements;
};
#endif // STACK_H_