Programming Resources
For Fun and Learning
Charles Cusack
Computer Science
Hope College
main

Python

C++


JAVA
PHP
SQL
Assignments

Stack


stack.cpp

//-----------------------------------------------------------------------
// stack.cc
//-----------------------------------------------------------------------
// Stack class
// Written by Charles A. Cusack, January 2000 
//
// This is a class for the stack data structure.  
//
//-----------------------------------------------------------------------
#include "stack.h"
//-----------------------------------------------------------------------
Stack::Stack(int s) {                             // Initialize the stack
      size = s;
      stack = new int[size]; // Allocate the necessary memory
      top = -1;              // Stack is empty
      }
Stack::~Stack() {            // The destructor frees the allocated memory
    delete []stack;
    }

int Stack::Push(int v) {                       // Place item on the stack
                                   //Return 1 if successful, and 0 if not
     if( !Full() )  {                      // Make sure stack is not full
        top++;                                    // Move the top pointer
        stack[top] = v;                      // insert element into stack
        return 1;                     // regular termination, so return 1
       }
     else return 0;                        // Stack was full, so return 0
     }

int Stack::Pop() {          // Remove top from stack and return its value 
    if( !Empty() ) {                      // Make sure stack is not empty
       return stack[top--];   // Return the value at the top of the stack
                              // and move the top counter
       }
    else return -1;                          // Empty stack, so return -1
    }

int Stack::Empty() {    // If the top=-1, stack is empty.
   return (top==-1); 
   }

int Stack::Full() {  // If top=size, stack is full.
   return (top+1==size);
   }
//-----------------------------------------------------------------------