Implementation of stack using arrays / Stack Operations using Arrays

A stack data structure can be implemented using a one-dimensional array. But stack implemented using array stores only a fixed number of data values. This implementation is very simple. Just define a one dimensional array of specific size and insert or delete the values into that array by using LIFO principle with the help of a variable called 'top'. Initially, the top is set to -1.

Whenever we want to insert a value into the stack, increment the top value by one and then insert. Whenever we want to delete a value from the stack, then delete the top value and decrement the top value by one.

Operations

A stack is LIFO. Last inserted item in the stack is deleted first. There are three basic stack operations: push(), pop(), peek().

a) push(item) operation:

This operation is used to add elements to the stack structure. Before inserting elements into stack, one needs to check, if there is space to add new element. If stack is full, trying to perform push operation causes an exception “StackOverFlow”.

Algorithm:

Input: The new item to be pushed on to it.
Output: A stack with a newly pushed item at the top position.
Data Structure: array representation of stack.
Steps:
1. If top is greater than or equal to size then
2. print “ stack us full”
3.else
4. top=top+1
5. a[top]=item
6.endIf
7.stop

b) pop() operation

This operation is used to delete element from stack. Before performing the pop operation you need to check whether there are data items in the stack are not. If there are no data items, performing the pop operation will generate an exception “StackUnderFlow”

Algorithm:

Input: A stack with elements
Output: A stack without popped elements.
Data Structure: array representation of stack.
Steps:
1. If top is lessthan 1 then
2. print “ stack is empty”
3.else
4.item=a[top]
5.top=top-1;
6.endIf
7.stop

Peek() operation

This operation is used to print top most elements in the stack without deleting it.

Algorithm

Input: A stack with elements
Output: Returns the top most element in the stack.
Steps:
1.If top is lessthan 1
2. print “stack is empty”
3.else
4. print “ the top of the stack is”, a[top]
5.endIf
6.stop

Name

Email *

Message *

More

More

More

More

More

More