Page 143 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 143
Fundamentals of Data Structures
Notes The syntax used for the PUSH operation is:
PUSH (stack, item)
where stack is the name of the stack into which the item specified as the second argument is
placed at the top position of the stack.
Algorithm to push an item onto the stack is given below:
Step 1: [Check for stack overflow]
if tos >=MAXSTACK
print “Stack overflow” and exit
Step 2: [Increment the pointer value by one]
tos=tos+1
Step 3: [Insert the item]
arr[tos]=value
Step 4: Exit
Here, tos is a pointer which denotes the position of top most item in the stack. Stack is represented
by the array arr and MAXSTACK represents the maximum possible number of elements in the
stack.
POP function is used for deleting the elements from a stack. As we know that stack follows a
mechanism of LIFO, hence the last element to be inserted is the first element to be deleted. The
syntax used for the POP operation is:
POP(stack)
where stack is the name of the stack from which the item has to be removed, i.e. the element at
the topmost position of the stack is removed.
Algorithm to pop an element from the stack is given below:
Step 1: [Check whether the stack is empty]
if tos = 0
print “Stack underflow” and exit
Step 2: [Remove the top most item]
value=arr[tos]
tos=tos-1
Step 3: [Return the item of the stack]
return(value)
Consider a stack structure as given in Figure 9.5. After inserting (PUSH) an element (viz. 55) into
this stack, the contents of the stack after the PUSH operation is given in Figure 9.6.
Figure 9.5: Stack Structure
136 LOVELY PROFESSIONAL UNIVERSITY