DS & A(Stacks - Array Based)
| CHAPTER 12 |
So, we are finally done with List DS for now. And if you made it this far hats off to your determination. Let's start this new chapter with the very same determination. In today's chapter, you will be learning about a new DS called Stack. Now you might be familiar with the word Stack but let us see what it means in the world of DS & A.Stacks:
- Stacks are restricted version of Lists with the following restrictions:
- Data can only be inserted from the top. Data insertion is referred to as PUSH.
- Data can only be deleted from the top as well. Data Deletion is referred to as POP.
- Alternatively, PUSH and POP should always be executed on the same side of the Stack.
- A Stack follows the LIFO principle also known as FILO.
- The accessible element can be referred to as TOP.
Stack ADT:
- template<typename e> class Stack{
- public:
- //Function to insert a value at the pop of the Stack
- virtual bool push(const e& item) = 0;
- //Function to remove top-most Stack value
- virtual bool pop(e& item) = 0;
- //Function to Display the stack
- virtual void print() const= 0;
- };
Stack Implementation:
- Array-Based Implementation:
- #include <iostream.h>
- #include "name_of_the_StackADT_file.h"
- template<typename e>
- class AStack: public Stack<e>
- {
- int max_size;
- int top_index;
- e *stack_array;
- public:
- AStack(int temp_max_size = 0):
- max_size(temp_max_size),stack_array(new e[max_size]),top_index(0)
- {
- //Initialization done with member Initializer List
- }
- bool push(const e& push) override;
- bool pop(e& pop) override;
- void print() const override;
- };
- template<typename e>
- bool AStack<e>::push(const e& item)
- {
- if(top_index == max_size) return false;//when stack is full
- stack_array[top_index++] = item;
- return true;//on succesful push operation
- }
- template<typename e>
- bool AStack<e>::pop(e& item)
- {
- if(top_index == 0) return false;//when stack is empty
- item = stack_array[--top_index];
- return true;//on successful pop poperation
- }
- template<typename e>
- void AStack<e>::print() const
- {
- std::cout<<"< ";
- int counter = top_index;
- while(counter != 0)
- std::cout<< stack_array[--counter]<<" ";
- std::cout<<">";
- }
- Testing the Implementation:
- int main()
- {
- AStack <int>newStack(10);
- newStack.push(12);
- newStack.push(15);
- newStack.push(22);
- newStack.push(32);
- newStack.push(14);
- newStack.push(45);
- newStack.push(67);
- newStack.push(76);
- newStack.push(87);
- newStack.push(95);
- int poppedValue;
- std::cout<<"\nPush Order is: 12->15->22->32->14->45->67->76->87->95";
- std::cout<<"\nPop Order is : ";
- for (int i = 0; i<10 ; i++)
- {
- newStack.pop(poppedValue);
- std::cout<<poppedValue<<((i<9)?"->":"");
- }
- std::cout<<"\n";
- }
( If you like the content here, follow TSP on social media to get notified on future updates)
Comments
Post a Comment