Tuesday, September 15, 2009

Stack in Arrays

Today's lecture was about stack. In a stack, the value that is inserted in the end is given out first, hence it is caled a LIFO (Last in First Out). The code for the stack implemented in a class is given below. You must note that I am returning the character value in pop whereas I had done the pop function differently in class. The point being, you can implement it many ways, just do it the way you like, are comfortable with or asked to do in a quiz or an assignment.

class Stack
{
private:
char* data; //character pointer
int head; //index counter
int maxSize; //maximum array size
public:
Stack(int);
void push(char);
char pop();
};

Stack::Stack(int num)//Constructor
{
head = -1; //setting head to -1;
maxSize = num;
data = new char[maxSize]; //declaring the stack size
for(int i = 0; i < maxSize ;i++) //initialising all values to NULL
{
data[i] = '\0'; //putting NULL values in the data array
}
}

void Stack::push(char c)//Adding a value
{
if(head == -1)
{
head++;
data[head] = c;
}
else if(head < maxSize - 1)
{
head++;
data[head] = c;
}
else
{
cout<<"Stack is full.";
}
}
char Stack::pop()
{
char c;
if(head==-1)
{
cout<<"Stack is empty.";
}
else
{
c = data[head];
head--;
}
return c;
}

No comments:

Post a Comment