Introduction to stacks

Hey Shouters!! Today, we will learn about stacks and implementation of stacks in C++.

In the earlier blogs, we have done the most important data structures Linked List. In this blog we will be discussing stacks data structure using linked list. So, if you haven’t seen linked list, i will suggest you to go through Linked list blog.

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).

One of the real life example of stacks is plates in the kitchen which are put on top of each other. Now the plate which is put in the last will be removed first thus following LIFO

In data structure, the stacks can be implemented via both arrays and linked list. In this blog we will implement stacks via linked list.

Stacks basically contain only two functions-

  1. Push()
  2. Pop()

Push() is basically inserting the data into the stack and pop is removing the data from the stack. We dont need to specify data in pop() function as it will always remove the top most data available

Implementation of Stacks in C++

This code will create a new node and id you dont understand this code, i will suggest you to go to my linked list blog.

Creating a node

Pushing the data

This code will tell about the insertion of data into the stack. We basically push the data into the stack and make it root. root is basically the top element of the stack.

implementation of stacks in C++

Pop the data

This code shows the popping of data from the stack. We pop the top element and assignes root or top to the next element below it in the stack.

implementation of stacks in C++

Compelete code

The compelete code of the stack is given as follow

implementation of stacks in C++

So, in this blog, we learned about stacks. If anybody has felt any problems with how these nodes are created, I suggest they visit the linked list blog first.

We daily add Multiple Choice Questions for placement preparation questions and technical interview preparation on the Instagram page. Check the Instagram account: Shout Coders

Happy learnings!!!!!!

Recommended Posts –

  1. Introduction to C language
  2. Structure of C program
  3. C Program to add two numbers
  4. C Program to reverse a number
  5. Difference between C and C ++.

Leave a Reply

Your email address will not be published. Required fields are marked *

Close Bitnami banner