DS & A(Stacks - Pointer Based)
| CHAPTER 13 |
In the previous chapter, we talked about Array Based Stacks so continuing our discussion on Stacks, In this chapter, we will see how to implement pointer-based Stacks also known as Linked Stacks.Visual Representation:
Properties of Linked Stack:
- Follows LIFO principle and all the other general properties of a stack.
- Unlike Array-based stack it's size is not fixed. Its size grows with the addition of new elements.
- A Linked Stack can have head and tail pointers but it is not mandatory.
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:
- Creating the Node:
- public:
- template<typename e>class Node
- {
- public:
- e element;
- Link<e>* next;
- Link(e elemValue = 0, Link<e>* nextValue = nullptr)
- {
- element = elemValue;
- next = nextValue;
- }
- Link(Link<e>* nextValue = nullptr)
- {
- next = nextValue;
- }
- };
NOTE: It's pretty clear after looking at the code that we will be using singly linked node. Can you
guess why Singly Linked and not Doubly Linked node?
- Pointer-Based Implementation:
- #include"Stack.h"
- #include"Link.h"
- #include <iostream>
- template <typename E>class LStack:public Stack<E>
- {
- Link<E>* top;
- int Size;
- public:
- LStack()
- {
- top = nullptr;
- Size = 0;
- }
- ~LStack()
- {
- delete top;
- }
- int getSize() const {return Size;}
- bool Push(const E&);
- bool Pop(E&);
- void Print() const;
- };
- template<typename E>
- bool LStack<E>:: Push(const E& item)
- {
- top = new Link<E>(item,top);
- Size++;
- return true;
- }
- template<typename E>
- bool LStack<E>:: Pop(E& item)
- {
- if(Size == 0) return false;
- item = top->element;
- Link<E>* temp = top->next;
- delete top;
- top = temp;
- Size--;
- return true;
- }
- template<typename E>
- void LStack<E>:: Print() const
- {
- Link<E>* temp = top;
- std::cout<<"< ";
- while(temp != nullptr)
- {
- std::cout<<temp->element<<" ";
- temp=temp->next;
- }
- std::cout<<">";
- }
- Testing the Implementation:
- #include "LStack.h"
- int main()
- {
- LStack<int> newStack;
- newStack.Push(32);
- newStack.Push(25);
- newStack.Push(67);
- newStack.Push(34);
- newStack.Push(56);
- newStack.Push(76);
- newStack.Push(32);
- newStack.Push(398);
- newStack.Push(36);
- std::cout<<"Original Stack : ";
- newStack.Print();
- int tempSize = newStack.getSize();
- int tempPoppedValue = 0;
- while(tempSize != 0)
- {
- newStack.Pop(tempPoppedValue);
- std::cout<<"\nAfter removing "<<tempPoppedValue<<" :";
- newStack.Print();
- tempSize--;
- }
- }
( If you like the content here, follow TSP on social media to get notified on future updates)
Comments
Post a Comment