Professional Documents
Culture Documents
Data Structure and Algorithms - Stack
Data Structure and Algorithms - Stack
The stack follows the LIFO (Last in - First out) structure where the last element
inserted would be the first element deleted.
Stack Representation
A Stack ADT allows all data operations at one end only. At any given time, we can
only access the top element of a stack.
The most fundamental operations in the stack ADT include: push(), pop(), peek(),
isFull(), isEmpty(). These are all built-in operations to carry out data manipulation
and to check the status of the stack.
Stack uses pointers that always point to the topmost element within the stack,
hence called as the top pointer.
Insertion: push()
push() is an operation that inserts elements into the stack. The following is an
algorithm that describes the push() operation in a simpler way.
Algorithm
1 − Checks if the stack is full.
2 − If the stack is full, produces an error and exit.
3 − If the stack is not full, increments top to point next empty space.
4 − Adds data element to the stack location, where top is pointing.
5 − Returns success.
Deletion: pop()
pop() is a data manipulation operation which removes elements from the stack. The
following pseudo code describes the pop() operation in a simpler way.
Algorithm
1 − Checks if the stack is empty.
2 − If the stack is empty, produces an error and exit.
3 − If the stack is not empty, accesses the data element at which top is pointing.
4 − Decreases the value of top by 1.
5 − Returns success.
peek()
The peek() is an operation retrieves the topmost element within the stack, without
deleting it. This operation is used to check the status of the stack with the help of
the top pointer.
Algorithm
1. START
2. return the element at the top of the stack
3. END
isFull()
isFull() operation checks whether the stack is full. This operation is used to check
the status of the stack with the help of top pointer.
Algorithm
1. START
2. If the size of the stack is equal to the top position of the stack, the stack is full. Return 1.
3. Otherwise, return 0.
4. END
isEmpty()
The isEmpty() operation verifies whether the stack is empty. This operation is used
to check the status of the stack with the help of top pointer.
Algorithm
1. START
2. If the top value is -1, the stack is empty. Return 1.
3. Otherwise, return 0.
4. END