« Stacks Using Arrays
Stacks
- Stack is a linear data structure like our arrays and LinkedList.
- Stacks are abstract data type: meaning we can insert or delete elements from the stack in a very specific way unlike arrays and LinkedList. Random operatios are not allowed in Stacks.
StackUsingArrayUse.cpp
1#include <iostream>2#include <iomanip>3#include <algorithm>4#include <string>5#include <cstring>6#include <vector>7#include <cmath>8#include <map>9#include <climits>10// climits for INT_MIN11#include <unordered_map>12using namespace std;13#include "StackUsingArray.cpp"14int main()15{16 // StackUsingArray s(4);17 // StackUsingArray s;18 // s.push(10);19 // s.push(20);20 // s.push(30);21 // s.push(40);22 // s.push(50);2324 // cout << s.size() << endl;25 // cout << s.top() << endl;2627 // cout << s.pop() << endl;2829 // cout << s.top() << endl;30 // cout << s.size() << endl;3132 // cout << s.isEmpty() << endl;3334 StackUsingArray<char> s;35 s.push(100);36 s.push(101);37 s.push(102);38 s.push(103);39 s.push(104);4041 cout << s.size() << endl;42 cout << s.top() << endl;4344 cout << s.pop() << endl;4546 cout << s.top() << endl;47 cout << s.size() << endl;4849 cout << s.isEmpty() << endl;5051 return 0;52}
StackUsingArray.cpp
1#include <climits> //as we use INT_MIN2template <typename T>34class StackUsingArray5{6private:7 T *data;8 int nextIndex;9 int capacity;1011public:12 StackUsingArray()13 {14 data = new T[4];15 nextIndex = 0;16 capacity = 4;17 }1819 int size()20 {21 return nextIndex;22 }2324 bool isEmpty()25 {26 return (nextIndex == 0);27 }2829 void push(T element)30 {31 if (nextIndex == capacity)32 {33 // cout << "Stack full!" << endl;34 // return;35 T *newData = new T[2 * capacity];36 for (int i = 0; i < capacity; i++)37 {38 newData[i] = data[i];39 }40 capacity = 2 * capacity;41 delete[] data;42 data = newData;43 }44 data[nextIndex] = element;45 nextIndex++;46 }4748 T pop()49 {50 if (isEmpty())51 {52 cout << "Stack is empty!" << endl;53 // return INT_MIN;54 return 0; // why 0 because 0 is a standard value which can be used for any data type55 // for int and double it will work for bool it will be false for char it will for 0 ASCII value which is null56 // for pointers it will be treated as null pointer57 }58 nextIndex--;59 return data[nextIndex];60 }6162 T top()63 {64 if (isEmpty())65 {66 cout << "Stack empty!" << endl;67 // return INT_MIN;68 return 0;69 }70 return data[nextIndex - 1];71 }72};