Concept of stack

Representation of stack using array:

Declaration 1:

#define size 100
int stack[size], top=-1;

In the above declaration stack is nothing but an array of integers,And most index of that array will act as a top.


The stack is of the size 100.As we insert the numbers,the top will get incerement .the elements will be placed from 0th position in the stack.At the most we can store elements in the stack,so at the most last element can be at (size -1) position,index 99.

Declaration 2:

#define size 10
struct stack
{
  int s[size];
  int top;
}st;

above declaration stack is declared as a structure.


Now compare declaration 1 and 2.both are of stack declaration only.But the second declaration will always preferred.WHY?
Because in the second declaration we have used a structure for stack elements and top,By this we are binding or co-relating top variable with stack elements.Thus top and stack are associated with each other by putting them together in a structure.The stack can be passed to the function by simply passing the structure variable.

We will make use of the second method of representing the stack in our program.

  • The stack can also be used in the database.For example if we want to store marks of all the students of fourth semester we can declare a structure of stack as follows:



Thus we can store the data about whole class in our stack.The above declaration means creation of stack. Hence we will write only push and pop function to implement the stack.And pushing or popping we should check whether stack is empty or full.

key point= IF top = MAXSIZE means stack is full.

stack empty operation

Initially  stack is empty.At that time the top should be initialized to -1 or 0.If we set top to -1 initially then the stack will contain the elements from 0th position and if we set top to 0 initially the elements will be stored from 1st position,in the stack.
Elements may be pushed onto the stack and there may be a case that will the elements are removed from the stack.Then the stack becomes empty.thus whenever top reaches to -1 we can say the stack is empty.

int stempty()
{
 if(st.top==-1)
return 1;
else
return 0;
}

stack full operation

In the representation of stack using array means size of stack.As we go on inserting the elements the stack gets filled with the elements.
So it is necessary before inserting the elements to check whether the stack is full or not.stack full condition is achieved when stack reaches to maximum size of array.

int stfull()
{
if(st.top>=size-1)
return 1;
else
return 0;
return 0;
}
 push operation:

push is function which inserts new elements at the top of the stack.

void push()
{
st.top++;
st.s[st.top]=item;
}



pop operation:

 which deletes the elements at the top of the stack.

 int pop()
{
int item;
item=st.s[st.top];
st.top--;
return[item];
}



1 comment:

Copyright © 2013 free coding