Back to Code List
c++

Stack

A simple implementation of a stack structure using an array. This includes a push and pop functions.

   main.cpp

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

class Stack
{
	private:
		int *stackArray;
		int capacity;// the size of the array stackArray
		int top;

	public:
		Stack(int capacity_input);
		~Stack() {delete [] stackArray;}
		void push (int x);//push a new value x
		int pop (); 
		bool isEmpty() const;//check whether the stack is empty
		bool isFull() const;//check whether the stack is full
};

Stack::Stack(int capacity_input)
{
	// set the capacity
	capacity = capacity_input;
	// dynamically create an array of size equal to ''capacity''
	stackArray = new int[capacity];
	top = 0;
}

bool Stack::isEmpty() const
{
	if (top == 0)
		return true;
	else
		return false;
}

bool Stack::isFull() const
{
	if (top == capacity)
		return true;
	else
		return false;
}

int Stack::pop()
{
	if (!isEmpty()) {
        --top;
		return stackArray[top];
	}
	return -1;
}

void Stack::push(int x)
{
	if(!isFull())
    {
		stackArray[top]=x;
		top++;
    }
}



const int STACK_SIZE = 30;  

int main()
{
	Stack stack(STACK_SIZE); 
	string inputFileName = "input.txt"; // input file with operations 
	string outputFileName = "output.txt"; // output file

	//open files
	ifstream inputFile;
	inputFile.open(inputFileName.c_str());
	if (!inputFile)
	{
		cout << "Error opening the file " << inputFileName << endl;
		exit(0);
	}
	
	ofstream outputFile;
	outputFile.open(outputFileName.c_str());
	
	if (!outputFile)
	{
		cout << "Error opening the file " << outputFileName << endl;
		exit(0);
	}


	//read operations from the input file
	string op;
	int value;
	while(inputFile >> op)
	{
		if (op == "pop") // a pop operation, 
			outputFile << stack.pop() << endl;// the pop result is print in the output file
		else // a push operation
		{
			inputFile >> value;
			stack.push(value);
		}
	}

	inputFile.close();
	outputFile.close();

	return 0;
}    

   input.txt

push 23 
push 34 
push 56 
push 1
push 323 
pop
pop
push 22
pop
push 987
push 345
push 234
pop
pop
pop
push 100
push 200
push 340
pop
push 987
push 345
pop    

   output.txt

323
1
22
234
345
987
340
345