Wednesday, 28 September 2016

2.) Stack

Hello guyz ,  this  time  I am writing about Stacks in c++

Stack is one  of  the data structures which is also a container of C++ stl .  
We all  have seen somewhat use of  stack in our day to day life . For more clarity , Let's assume there is a pile of plates in a party i.e one plate is on the  top of the other. If someone needs a plate , He removes the plate which is  on the top And if someone wants to add a plate in that pile He pus it on the top . So this is  a practical example of a stack.
Stack has the property of LIFO i.e the Last element is the First one to  come out as it was there in the previous example of  pile of the plates .

In programming word  -- Stack is an area of memory that holds all local variables and parameters used by any function, and remembers the order in which functions are called so that function returns occur correctly.
 Each time a function is called, its local variables and parameters are “”pushed onto”” the stack.
When the function returns, these locals and parameters are “”popped.””
Because of this, the size of a program’s stack fluctuates constantly as the program is running, but it has some maximum size.
A Stack has mainly two operations 1.)Push      2.)Pop

There are  many questions in competitive coding  where we need to implement Stack .

I will show the implementation of  stack in c++ stl . If you want to see the basic  coding  of implementing a stack ,, google it :) .

#include <iostream>      
#include <stack>          // we need  to implement the stack from stl library 
using namespace std;

int main ()
{
  stack<int> mystack;                    // you  can  store  any type of data 

  for (int i=0; i<5; ++i) 
{
       mystack.push(i);                     // push()   function puts data on the top of other in stack
}

cout << "Popping out elements...";
  while (!mystack.empty())                  //  returns true if  your stack is not empty
  {
     std::cout << ' ' << mystack.top();       // the top  value on the  stack  is accessed by .top() function
     mystack.pop();                                //  removes out the top value  present in the stack  thus making the next one element                                                              //the top one 
  }
  std::cout << '\n';

  return 0;
}

output :   4 3 2 1 0


If you want to practice questions regarding stack ,, google some of the tagged question  with stack .  while you  can try this one . This is a very good and easy  question regarding implementation  of stack  -  try this

No comments:

Post a Comment