#include #include "stack.h" // ---------------------------------------------------------------------- // The StackNode class implements individual nodes of a stack. There are // two member variables -- a value, and a pointer to the next node in the // stack (NULL if there is no next node.) class StackNode { public: StackNode(Jval, StackNode *); // Create a new node with given val and next ~StackNode(); Jval val; StackNode *next; }; StackNode::StackNode(Jval v, StackNode *n) { val = v; next = n; } StackNode::~StackNode() { if (next != NULL) delete next; } // ---------------------------------------------------------------------- // Ok -- now, the stack class implementation. These should all be // straightforward to you. Stack::Stack() // Create an empty stack { top_node = NULL; } Stack::~Stack() // Destroy a stack { if (top_node != NULL) delete top_node; } void Stack::push(Jval v) { top_node = new StackNode(v, top_node); } Jval Stack::pop() { StackNode *tmp; Jval v; if (top_node == NULL) { fprintf(stderr, "ERROR: Trying to pop empty stack\n"); // exit(1); } tmp = top_node; v = tmp->val; /* Unhook the top node */ top_node = tmp->next; /* Delete the top node */ tmp->next = NULL; delete tmp; return v; } Jval Stack::top() { if (top_node == NULL) { fprintf(stderr, "ERROR: Trying to get the top of an empty stack\n"); // exit(1); } return top_node->val; } bool Stack::isEmpty() { return (top_node == NULL); }