CodersZone logo

Stack Implementation

A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop.
The functions associated with stack are:
  1. empty()-Returns whether the stack is empty-Time Complexity:O(1)
  2. size() – Returns the size of the stack – Time Complexity: O(1)
  3. top() / peek() – Returns a reference to the topmost element of the stack – Time Complexity: O(1)
  4. push(a) – Inserts the element ‘a’ at the top of the stack – Time Complexity: O(1)
  5. pop() – Deletes the topmost element of the stack – Time Complexity: O(1)

Algorithm

    Push Operation 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.

    Pop Operation 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.

Code

                # Python program to demonstrate stack implementation using list

                stack = [ ]
                
                # append() function to push
                # element in the stack
                stack.append('a')
                stack.append('b')
                stack.append('c')
                
                print('Initial stack')
                print(stack)
                
                # pop() function to pop
                # element from stack in
                # LIFO order
                print('\nElements popped from stack:')
                print(stack.pop())
                print(stack.pop())
                print(stack.pop())
                
                print('\nStack after elements are popped:')
                print(stack)
                
                # uncommenting print(stack.pop())
                # will cause an IndexError
                # as the stack is now empty
                 
            

Output

                
Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Stack after elements are popped [ ]
See the same program in Java See the same program in C