Stack is type of data structure which can be visualised as the stack of dishes placed over the top of one another. This kind of data structure is called as linear type data structure primarily because the nature of it’s handling the data in serealized format, meaning the grouping or placement of data is linear format one after another. In most of the cases where we want to store the data in group and perform the Last In First Out type of operations we perfer using Stack data structure the e.g are -

  • In browsers (Back button in browser, first click on the button return the last visited page)
  • To reverse a word (pretty simple example)
  • Your backpack (An real life example, imagine your full packed bagpack, the first thing you’ll put of a packed bagpack is the thing you have put their in the last place on top of everything)

Now there are primarily 4 kind of operation we can run over stack, those are -

  • Push (For inserting the new element/data on top of the stack)
  • Pop (For removing the element from the stack, this will remove the element from the top only)
  • Peak (For reading the value of the topmost element in the stack without removing it from the stack)
  • isEmpty (To check if the stack is empty and don’t have any elements)
  • isFull (To check if the stack is full and can’t have anymore elements)

How to initialize the stack in a program ?

The stack data structure is of an abstract data type structure also known as an ADT. This kind of abstract data structure is ideally not comes predefined with the language but usually comes as in part of some pre-defined library from where user can make a call it as new Object Type and can initialize the stack type data structure, but using the stack ds in this way is more aligned practise of day-to-day usuage of an software engineer or developer. For requirements of an interviews and competitive programming one must know how to initiate and create the stack data strcuture without using pre-defined library’s. Some pre-defined library which comes with stack ds are

  • STL or commonly known as Standard Template Library in C++

For our purposes lets deep down in how create and initialize stack data strucutre

  1. Created a pointer called TOP, whose primary objective is to keep the track top-most element in the stack
  2. While initializing the stack we’ll assign the value of TOP to be -1 so that we can check if the stack is empty by comparining TOP == -1
  3. On pushing the new element in the stack we increase the value of TOP by +1, and appoint the new value to the position provide by the TOP
  4. On popping we return the value on the position provided by the TOP and reduced value of TOP by -1
  5. We check for isEmpty() before popping the element
  6. We check for the isFull() before pushing the new element

The time complexity

For the array based implementation of the Stack it takes constant time for push and pop operation i.e O(1)