In this STACK Operation Article, A STACK is defined formally as a list (a linear DATA STRUCTURE) in which all insertion and deletions are made at one end called the Top Of Stack (TOS). The fundamental operations, which are possible on a stack, are:
The most recently pushed element can be checked prior to performing a pop operation. A stack is based on the Last In First Out algorithm (LIFO) in which insertion and deletion operations are performed at one end of a stack. Also, the information can only be removed in the opposite order in which it was added to the stack. The most accessible information in a stack is at the top of stack and least accessible information is at the bottom of the stack.
For example, consider a stack of plates on the counter in a cafeteria. During the dinner time customers take plates from the top of the stack and waiter puts the washed plates on the top of the stack. The plate that is put most recently on the stack is the first one to bed taken off. The plate at the bottom is the last one to be used.
A pointer TOS keeps track of the top most information in the STACK. Initially when the stack is empty, TOS has a value zero and when the stack contains a single information TOS has a value one and so on. Before an item is pushed onto the stack, the pointer is incremented by one. The pointer is decrements by one each time a deletion is made from the stack.
Push means to insert an item onto the stack. The push algorithm is illustrated below. The algorithm illustrated inserts an item to the top of stack, which is represented by array S and containing Size number of items with a pointer Tos denoting the position of top most item in the stack.
|Step 1 : [check for stack overflow]
If Tos >= Size
Output “Stack is Overflow” and exit
Step 2 : [Increment the Pointer value by one]
Tos = Tos + 1
Step 3 : [perform insertion]
S[Tos] = Value
Step 4 : Exit
if(tos >= SIZE)
printf(“The STACK is Full….\n”);
printf(“Enter the New Value :”);
The pop operation deletes or removes the topmost item from the stack. After removal of top most information, new value of the pointer Tos becomes the previous value of Tos that is Tos = Tos – 1 and freed position is allocated to free space. The algorithm to remove an item from the stack is illustrated below.
|Step 1 :[check whether the stack is empty]
If Tos = 0
Output “Stack underflow” and exit
Step 2 :[Remove the Tos information]
Value = S[Tos]
Tos = Tos – 1
Step 3 :[Return the former information of the stack]
if(tos <= 0)
printf(“The STACK is Empty….\n”);
remitem = arr[tos];
printf(“The Removeble item is %d.\n”,remitem);