Somewhat generic stack code. Data is an int for simplicity. It should work, but I make no guarantees!!
/*
stack.h - header file for a stack data structure.
*/
#ifndef STACK_H
#define STACK_H
#include <stdlib.h>
#include <iostream.h>
class node;
class stack;
class node
{
friend stack;
private:
int data;
node *link;
};
class stack
{
public:
stack();
~stack();
int peek();
int pop();
void push( int loc );
bool isEmpty();
int size();
private:
node * first;
bool empty;
int howBig;
};
#endif //STACK_H
/*
stack.cpp
source code for a stack data structure, implemented using a linked list
*/
#include "stack.h"
stack::stack()
{
first = new node;
first->link = 0;
//empty = true;
howBig = 0;
}
stack::~stack()
{
node * next;
while ( first != 0 ) {
next = first->link;
delete first;
first = next;
}
}
int stack::peek()
{
return first->data;
}
int stack::pop()
{
if ( ! isEmpty() ) {
int x = first->data;
node *temp = first;
first = first->link;
howBig--;
delete temp;
return x;
} else {
cerr << "Stack is empty.\n";
exit( 1 );
return 0; // MSVC insists that all control paths must
// return a value. Duhhh...
}
}
bool stack::isEmpty()
{
return ( first == 0 );
}
void stack::push( int loc )
{
empty = false;
node *temp = new node;
temp->data = loc;
temp->link = first;
first = temp;
howBig++;
return;
}
int stack::size()
{
return howBig;
}