DTL

Stack

Introduction

The stack data structure follows the LIFO (Last In First Out) principle. That is, the element added last will be removed first. Stack uses an encapsulated object of either vector or deque (by default) or list as its underlying container, providing a specific set of member functions to access its elements.

Advantages

  • Fast insertion, deletion and access operations.
  • Can be used to solve problems that work with recursion.

Disadvantages

  • Limited number of methods.
  • Random access of elements is impossible in stacks.
  • Stacks are neither flexible nor scalable.

Using stack with DTL

Initializing a stack

  1. Implementation using an array:
  2. #include "stack.hpp"
    #include <iostream>
    
    int main() {
      // Static
      dby::Stack<int> staArrStack(5); // MAX CAPACITY = 5
    
      // Pointer
      dby::Stack<int>* ptrArrStack = new dby::Stack<int>(5); // MAX CAPACITY = 5;
      delete ptrArrStack;
    
      return 0;
    }
  3. Implementation using a linked list:
  4. #include "stack.hpp"
    #include <iostream>
    
    int main() {
      // Static
      dby::Stack<int> staListStack;
    
      // Pointer
      dby::Stack<int>* ptrListStack = new dby::Stack<int>();
      delete ptrListStack;
    
      return 0;
    }

Stack methods

Exclusive of array implementation

  • max_size(): Returns the max size of the stack.
  • full(): Returns whether the stack is full or not.

Both implementations

  • size(): Returns the current size of the stack.
  • empty(): Returns whether the stack is empty or not.
  • top(): Returns a reference to the top most element of the stack.
  • push(T data): Adds the element 'data' at the top of the stack.
  • pop(): Deletes the top most element of the stack.
  • extract(): Returns and deletes the top most element of the stack.
  • reverse(): Reverses the order of the elements in the stack.