A stack is a linear structure in which items may be added or removed only at one end.
Stack is also defined as a list of elements in which we can insert or delete the element only at the top of stack.
EXAMPLES OF STACK
A stack is a LIFO structure: Last In First Out
BASIC OPERATIONS WITH STACKS
The two operations applicable to all stacks are:
a push operation, when we add the item in stack.
a pop or pull operation: when we delete the item from stack.
Another helper operation top (also known as peek or peak ) can return the current top element of the stack without removing it from the stack.
Adds new data element to the top of the stack
Removes a data element from the top of the stack
Checks the top element. Stack is not changed
CONDITIONS OF STACK
Overflow: It may be possible that a condition arises when there is no place for adding(push) the element in stack. This is called overflow.
Underflow: The second possibility arises when there is no element for deleting(pop) from stack. This is called underflow.
IMPLEMENTING STACK WITH ARRAY
Since stack is a collection of same type of elements, so we can take array for implementing stack. In array we can added or deleted at any place and we want to push and pop the element from the top of stack only. So we can take a pointer variable TOP, which keeps the position of top element in array and a variable MAXSTK which gives the maximum number of elements that can be held by the stack. The condition TOP=0 or TOP=NULL will indicate that the stack is empty.
means: if TOP=0 or NULL that’s means stack is empty
and if TOP = MAXSTK that’s means stack is full.
ARRAY REPRESENTATION OF STACK
0 1 2 3 4 5 6
Here stack is implemented with array, size of array is 7. the value of TOP is 2
Suppose we want push an element in stack then the value of top is 3 and and array representation will be …
20 5 10 15 5 10 15
ALGORITHM ( PUSH OPERATION)
This procedure pushes an item onto a stack.
We consider 2 variables in following algorithm i.e
TOP which contain the location of last inserted element of stack.
MAXSTK= max number of elements store in stack.
Step1: If TOP=MAXSTK, then Print Overflow and Return.
Step2: Set Top=Top+1 [increase top by 1]
Step3: Set Stack[TOP]= ITEM [insert new item in stack].
Step4: Return or Exit .
ALGORITHM ( POP OPERATION)
This procedure deletes the top element from Stack.
Step1 . If TOP<=0 then print Underflow & Return.
Step2. Delete STACK[TOP] (delete the top most item from stack).