Skip to main content

Stack Data Structure

Stack

In this blogpost we are going to learn about Stack. What is the stack? What is the LIFO? What are stack operations? What is the pop operation ?, What is the push operation?, How to perform push/pop operation on stack? and conversions using stack.

stack

Defination of stack

Stack is a linear data structure which follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out).

There are many real-life examples of a stack. Consider an example of plates stacked over one another in the canteen. The plate which is at the top is the first one to be removed, i.e. the plate which has been placed at the bottommost position remains in the stack for the longest period of time. So, it can be simply seen to follow LIFO(Last In First Out)/FILO(First In Last Out) order.


Basic Operations on Stack

  • push() − Pushing (storing) an element on the stack.
  • pop()<− Removing (accessing) an element from the stack.

To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following functionality is added to stacks −

  • peek() − get the top data element of the stack, without removing it.
  • isFull() − check if stack is full.
  • isEmpty() − check if stack is empty.

Push operation

The process of putting a new data element onto stack is known as a Push Operation. Push operation involves a series of steps −

  • Step 1 − Checks if the stack is full.
  • Step 2 − If the stack is full, produces an error and exit.
  • Step 3 − If the stack is not full, increments top to point next empty space.
  • Step 4 − Adds data element to the stack location, where top is pointing.
  • Step 5 − Returns success.

Procedure for push operation

  1. begin procedure push: stack, data
  2. if stack is full return null
  3. endif
  4. top ← top + 1
  5. stack[top] ← data
  6. end procedure

Code for push operation


Pop operation

Accessing the content while removing it from the stack, is known as a Pop Operation. In an array implementation of pop() operation, the data element is not actually removed, instead top is decremented to a lower position in the stack to point to the next value.

But in linked-list implementation, pop() actually removes data element and deallocates memory space.


Pop operation may involve the following steps

  1. Step 1 − Checks if the stack is empty.
  2. Step 2 − If the stack is empty, produces an error and exit.
  3. Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
  4. Step 4 − Decreases the value of top by 1.
  5. Step 5 − Returns success.

Algorithm for pop operation

  • begin procedure
  • pop: stack
  • if stack is empty return null
  • endif
  • data ← stack[top]
  • top ← top - 1
  • return data
  • end procedure

Algorithm for isfull()


Algorithm for isempty()

  1. begin procedure isempty
  2. if top less than 1 return true
  3. else return false
  4. endif
  5. end procedure

Code for isempty ()


Applications of stack

In a stack, only limited operations are performed because it is restricted data structure. The elements are deleted from the stack in the reverse order.

Following are the applications of stack:
  1. 1. Expression Evaluation
  2. 2. Expression Conversion
  3. i. Infix to Postfix
  4. ii. Infix to Prefix
  5. iii. Postfix to Infix
  6. iv. Prefix to Infix

Infix expression

Infix, Postfix and Prefix notations are three different but equivalent ways of writing expressions. It is easiest to demonstrate the differences by looking at examples of operators that take two operands.

Infix notation: X + Y Operators are written in-between their operands. This is the usual way we write expressions. An expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C together, then multiply the result by A, then divide by D to give the final answer."


Infix notation needs extra information to make the order of evaluation of the operators clear: rules built into the language about operator precedence and associativity, and brackets ( ) to allow users to override these rules.

For example, the usual rules for associativity say that we perform operations from left to right, so the multiplication by A is assumed to come before the division by D. Similarly, the usual rules for precedence say that we perform multiplication and division before we perform addition and subtraction


Postfix notation

Postfix notation (also known as

"Reverse Polish notation"): X Y + Operators are written after their operands. The infix expression given above is equivalent to A B C + * D / The order of evaluation of operators is always left-to-right, and brackets cannot be used to change this order. Because the "+" is to the left of the "*" in the example above, the addition must be performed before the multiplication.


Operators act on values immediately to the left of them. For example, the "+" above uses the "B" and "C". We can add (totally unnecessary) brackets to make this explicit: ( (A (B C +) *) D /) Thus, the "*" uses the two values immediately preceding: "A", and the result of the addition. Similarly, the "/" uses the result of the multiplication and the "D".


Prefix notations

Prefix notation (also known as "Polish notation"): + X Y Operators are written before their operands. The expressions given above are equivalent to / * A + B C D As for Postfix, operators are evaluated left-to-right and brackets are superfluous. Operators act on the two nearest values on the right. I have again added (totally unnecessary) brackets to make this clear: (/ (* A (+ B C) ) D)


Infix to postfix conversion

Infix to postfix Algorithm
  • 1) Scan the string from left to right
  • 2) Make three columns symbol , postfix expression and stack
  • 3) If symbol = = opening bracket push in stack (i.e put in stack column)
  • 4) If symbol = = closing bracket pop all the elements from stack till we get opening bracket, pop the opening bracket also and then put the pop elements in the postfix expression column leaving opening bracket.
  • 5) If symbol = = alphabet/ digit then put the symbol in postfix expression column
  • 6) If symbol = = operator check priority of top element in the stack.
  • If priority( top element)>= priority(symbol operator) then pop top element and put it in postfix expression column If priority( top element) priority(symbol operator) then push the symbol in the stack
  • 7) If all the symbol finished from the symbol pop all the elements from stack and put it in postfix expression column

Comments

Trending⚡

Happy birthday Hardik Pandya | In C programming

  Happy birthday Hardik Pandya . Now you are  28 years old. Great achievement you have. Let's we want to talk more about Hardik pandya. He is great cricketer. Pandya is awesome. In this Blog Post we are going to wish pandya " Happy birthday using C program". Let's tune with us till end. Now we have to wish pandya, so we are going to use printf () function printing message to pandya as " Happy birthday Hardik pandya Now you are 28 years old". Hardik pandya was born on 11 October in 1993. Now we are going to declare a variable called as current_age = 2021 - 1993. It calculate current age Of Hardik pandya. See the "Happy birthday pandya" using c programming. If you liked this Blog Post then don't forget to share with your computer science learning friends. Once again " Happy birthday Hardik Pandya sir". Read also Happy Rakshabandhan wish using C program Friendship day 2021 greetings in C

Understanding link.click() in JavaScript

Hey! Today i am going to share with you how to use link.click() function in javascript As a JavaScript developer, you may come across the need to programmatically click a link on a web page. The link.click() method is a commonly used way to do this, and it is important to understand how it works and when to use it. What is link.click()? link.click() is a method that can be used to simulate a click on a link element in JavaScript. It is typically used when you want to trigger a link click event programmatically, rather than requiring the user to physically click the link. How to use link.click() Using link.click() is relatively straightforward. First, you need to select the link element you want to click using a DOM selector such as getElementById() or querySelector(). Then, you can call the click() method on the link element to simulate a click. Here is an example: // select the link element const myLink = document.getElementById('my-link'); // simulate a cl...

Best course Recommendation of IT field in 2023

Recommend me best course 🎉50% Discount on registration today itself 🎉! Join Course Now In today's fast-paced digital age, staying updated with the latest technology trends is crucial for professionals looking to advance in their careers. With technology rapidly evolving, it is important to continuously upskill and gain new knowledge to stay relevant in the job market. In 2023, there are several courses in technology that are gaining popularity and are highly recommended for professionals seeking to enhance their skills in data science, analytics, and digital marketing. Data Science: Data science is an interdisciplinary field that combines statistical analysis, machine learning, and computer science to extract insights and knowledge from data. With the increasing amount of data available, data scientists are in high demand across various industries. The best courses in data science for 2023 are th...

Define a macro EQUALSTR which accepts two strings and compare equality of both string

Define a macro EQUALSTR which accepts two strings and compare equality of both string #include<stdio.h>  #include<string.h>  #define EQUALSTR(str1,str2) strcmp(str1,str2)?0:1  void main()  {  char str1[10],str2[10];  printf("\n Enter the two strings: ");  gets(str1);  gets(str2);  if(EQUALSTR(str1,str2))  printf("\n Strings are equal");  else  printf("\n Strings are not equal");  } Also Read C program to find largest of two numbers using Structure Predefined Macro program Macros vs Functions Preprocessor Syntax Task Performed by Preprocessor

check number is prime or odd or even using c program

Here is the c program to check if the user entered number is prime ,even and odd. These few lines of code solve three problems. In the above program we used integer type num variable for storing user entered numbers. Then we used the IF condition statement. That's all. IF condition for even number In the First IF statement we have a logic. If the number is divided by two then the reminder should be 0 then the number is an even number else not an even number. That simple logic is implemented in the first if statement. IF condition for odd number In the second IF statement we Implemented odd number logic. We identify odd numbers just by making little change in even number logic. If the number is divided by two then the reminder should not be a zero. Then the number is odd. That's simple logic used to identify whether a number is odd or not an odd number. IF condition for prime number In the third IF condition we implemented the logic of the prime number. In this IF ...

How to write programs in Bhai language

Bhai Language Bhai language is fun Programming language , with this language you can makes jokes in hindi. Bhai language written in typescript. It's very funny , easy and amazing language. Keywords of this language written in Hindi . Starting and ending of the program Start program with keyword " hi bhai " and end with " bye bhai ". It's compulsory to add this keyword before starting and end on the program. You write your programming logic inside this hi bhai and bye bhai . How to declare variables in Bhai language We use " bhai ye hai variable_name" keyword for declaring variables. In javascript we use var keyword for declaring variables but here you have to use " bhai ye hai " keyword. If you are declaring string then use " " double quotes. You can use Boolean variable like sahi and galat for true and false . How to print output in Bhai language You have to use " bol bhai " keyword for ...