stack1.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Link to challenge: https://www.w3resource.com/cpp-exercises/stack/index.php
#include <iostream>
#include <vector>
using namespace std;
class Stack{
private:
struct node{
int data;
node* next;
};
node* head = nullptr;
public:
Stack(){
}
Stack(std::vector<int> val){
for (int i = val.size() - 1; i >= 0; i--){
if (head == nullptr){
head = new node{val[i], nullptr};
}
else {
head = new node{val[i], head};
}
}
}
bool is_empty(){
if (head == nullptr){
return 1;
}
else {
return 0;
}
}
void insert_elements(std::vector<int> val){
for (int i = val.size() - 1; i >= 0; i--){
if (head == nullptr){
head = new node{val[i], nullptr};
}
else {
head = new node{val[i], head};
}
}
}
int remove_element(){
node* tmp = head;
head = head -> next;
tmp -> next = nullptr;
return tmp -> data;
}
int top(){
return head -> data;
}
void print(){
cout << "Stack Elements: ";
for (node* i = head; i != nullptr; i = i -> next){
cout << i -> data << " ";
}
cout << endl;
}
};
int main(){
cout << "Test Data:" << endl;
cout << "Create a stack object" << endl;
Stack s1;
cout << "Check if the stack is empty or not? ";
cout << s1.is_empty() << endl;
cout << "Insert some elements onto the stack:" << endl;
s1.insert_elements({4, 5, 6, 7});
s1.print();
cout << "Remove an element from the stack! ";
cout << s1.remove_element() << endl;
s1.print();
cout << "Top of the element of the stack:" << endl;
cout << s1.top() << endl;
return 0;
}
Console Output
1
2
3
4
5
6
7
8
9
Test Data:
Create a stack object
Check if the stack is empty or not? 1
Insert some elements onto the stack:
Stack Elements: 4 5 6 7
Remove an element from the stack! 4
Stack Elements: 5 6 7
Top of the element of the stack:
5