-
Notifications
You must be signed in to change notification settings - Fork 1
/
GStack.h
72 lines (64 loc) · 1.46 KB
/
GStack.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#pragma once
#include <iostream>
// This header file contains the Stack Class implementation for the
// self growable and self shrinking data structure
// with linked list
class GStack{
private:
struct Node{
int key;
struct Node *next = nullptr;
};
int size;
struct Node *stack;
public:
GStack();
~GStack();
void push(int n);
int pop();
void displayItems();
};
GStack::GStack(){
size = 0;
stack = nullptr;
}
GStack::~GStack(){
while (stack != nullptr)
{
struct Node* temp;
temp = stack;
stack = stack->next;
delete temp;
}
}
void GStack::push(int n){
struct Node *newHead = new Node{n, stack};
stack = newHead;
++size;
}
int GStack::pop(){
using namespace std;
if(stack == nullptr){
cout << "Empty Stack... returning zero" << endl;
return 0;
}
struct Node* temp = stack;
stack = stack->next;
int tempKey = temp->key;
delete temp;
--size;
return tempKey;
}
void GStack::displayItems(){
using namespace std;
cout << "Stack \n------------------" << endl;
cout << "Size: " << size << endl;
cout << "Stack Elements \n------------------" << endl;
struct Node *iter = stack;
while (iter != nullptr)
{
cout << iter->key << " ";
iter = iter->next;
}
cout << "\n------------------\n\n" << endl;
}