Sunday, April 26, 2009

6 - Stack

A Stack is a collection of items in which only the most recently added item may be removed. The latest added item is at the top. Basic operations are push and pop. Often top and isEmpty are available, too. Also known as "last-in, first-out" or LIFO (see NIST-DADS' definition of stack). We may think a stack is a cramp storage area, where the first item going in, will certainly last to comes out.

Basic operation of stack are :
  1. push
  2. pop
The program bellow is an example of simple stack operation :

#include "iostream"
using namespace std;

#define n 10
int Stack[n]; //declaring a stack
int Top; //declaring the Top index of a stack
int i; //general counter

void initialize(void)
{
Top = -1;
}

int stillunfilledup(void)
{
if (Top < n-1) //stack is not full yet
{
return 1;
}
else
{
return 0;
}
}

void push(int X)
{
Top =Top +1;
Stack[Top] = X;
}

int notempty(void)
{
if (Top > -1)
{
return 1;
}
else
{
return 0;
}
}

int pop()
{
int X=Stack[Top];
Top = Top -1;
return X;
}


int main(void)
{
int X;
int i;

initialize();


cin >> X;
while (X != 9999) //loop for pushing. As long as the user do not input 999, the loop runs
{
if (stillunfilledup()) //stack is not full yet
{
push(X);
}
else //stack is full
{
cout << "Stack is full";
break;
}
cin >> X;
}

cout << endl << endl << endl;
for (i = 0; i < n; i++)//loop for popping
{
if (notempty())
{
X = pop();
cout << "Pops the " << Top+1 << " th member" << X << endl;
}
else
{
cout << "empty";
}
}
}