« Stacks using linked list

Implement Stack using LinkedList

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_MIN
11#include <unordered_map>
12using namespace std;
13
14template <typename T>
15class Node
16{
17public:
18 T data;
19 Node<T> *next;
20
21 Node(T data)
22 {
23 this->data = data;
24 next = NULL;
25 }
26};
27
28template <typename T> // this line belongs to this class only. We might need to add this to each class
29class Stack
30{
31private:
32 int size;
33 Node<T> *head;
34
35public:
36 Stack()
37 {
38 head = NULL;
39 size = 0;
40 }
41
42 int getSize() const
43 {
44 return size;
45 }
46
47 bool isEmpty() const
48 {
49 return size == 0;
50 }
51
52 void push(T element)
53 {
54 Node<T> *newNode = new Node<T>(element);
55 newNode->next = head;
56 head = newNode;
57 size++;
58 }
59
60 T pop()
61 {
62 if (isEmpty())
63 {
64 return 0;
65 }
66 T ans = head->data;
67 Node<T> *temp = head;
68 head = head->next;
69 delete temp;
70 size--;
71 return ans;
72 }
73
74 T top() const
75 {
76 if (isEmpty())
77 {
78 return 0;
79 }
80 return head->data;
81 }
82};
83
84int main()
85{
86 Stack<char> s;
87 s.push(100);
88 s.push(101);
89 s.push(102);
90 s.push(103);
91 s.push(104);
92
93 cout << s.getSize() << endl;
94 cout << s.top() << endl;
95
96 cout << s.pop() << endl;
97
98 cout << s.top() << endl;
99 cout << s.getSize() << endl;
100
101 cout << s.isEmpty() << endl;
102 return 0;
103}