Implementation of Stack Data Structure - Programmrs

A stack is an ordered collection of data in which insertion and deletion operation is performed at only one end called the Top of the Stack (TOS).

The element last inserted will be the first to be deleted. Hence, the stack is known as the Last In First Out (LIFO) structure.



STACK

Stack Operations

  • Push: It is used to add an item to the top of the stack.
  • Pop: It is used to remove an item from the top of the stack.
  • Peek: It returns the element stored at the top of the stack
  • IsFull: Check if the stack is Full
  • IsEmpty: Check if the stack is Empty
  • Display: Print the entire stack

Initial value of top is -1 i.e., top = -1




Algorithm for Push and Pop Operation:


Push:

1. Start

2. If(top=size-1)


Print” Stack is full”


3. Otherwise,

i. Increase top by 1

ii. Read data and store it at the top position

4. Stop



Pop:

1. Start

2. If(top=-1)


Print” Stack is empty”


Otherwise,

3. Decrease top by 1

4. Stop


Working of Stack Data Structure


The operations work as follows:

  1. A pointer called TOP is used to keep track of the top element in the stack.
  2. When initializing the stack, we set its value to -1 so that we can check if the stack is empty by comparing TOP == -1.
  3. On pushing an element, we increase the value of TOP and place the new element in the position pointed to by TOP.
  4. On popping an element, we return the element pointed to by TOP and reduce its value.
  5. Before pushing, we check if the stack is already full
  6. Before popping, we check if the stack is already empty




Stack Time Complexity

For the array-based implementation of a stack, the push and pop operations take constant time, i.e.O(1).

Applications of Stack Data Structure

Although stack is a simple data structure to implement, it is very powerful. The most common uses of a stack are:

  • To reverse a word - Put all the letters in a stack and pop them out. Because of the LIFO order of the stack, you will get the letters in reverse order.
  • In compilers - Compilers use the stack to calculate the value of expressions like 2 + 4 / 5 * (7 - 9) by converting the expression to prefix or postfix form.
  • In browsers - The back button in a browser saves all the URLs you have visited previously in a stack. Each time you visit a new page, it is added on top of the stack. When you press the back button, the current URL is removed from the stack, and the previous URL is accessed.
  • Evaluation of postfix and prefix expression
  • Checking the Balanced Expression
  • Conversion of Postfix or Prefix to Infix Expression

Post a Comment

Previous Post Next Post