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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
// 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(){
}
// void insert_elements_reverse(std::vector<int> arr){
// for (int i = arr.size() - 1; i >= 0; i--){
// if (head == nullptr){
// head = new node{arr[i], nullptr};
// }
// else {
// head = new node{arr[i], head};
// }
// }
// }
void insert_elements(std::vector<int> arr){
for (int i = 0; i < arr.size(); i++){
if (head == nullptr){
head = new node{arr[i], nullptr};
}
else {
head = new node{arr[i], head};
}
}
}
void printReverse(){
cout << "Stack Elements: ";
for (node* i = head; i != nullptr; i = i -> next){
cout << i -> data << " ";
}
cout << endl;
}
void print(){
int count = 0;
node* i = head;
print(count, i);
}
void print(int count, node* i){
if (count == 0){
cout << "Stack Elements: ";
}
// BASE CASE
if (i == nullptr){
return;
}
// cout << "Test Read: " << i -> data << endl;
print(++count, i -> next);
cout << i -> data << " ";
// cout << "Count: " + to_string(count) << endl;
if (i == head){
cout << endl;
}
}
void remove_element(){
node* tmp = head;
head = head -> next;
tmp -> next = nullptr;
delete tmp;
}
};
int main(){
cout << "Test Data:" << endl;
Stack s4;
cout << "Input some elements onto the stack:" << endl;
s4.insert_elements({0, 1, 5, 2, 4, 7});
s4.print();
cout << "Display the reverse elements of the stack:" << endl;
s4.printReverse();
// s4.printReverse();
cout << "Remove two elements:" << endl;
s4.remove_element();
s4.remove_element();
s4.printReverse();
cout << "Input two more elements" << endl;
s4.insert_elements({-1, 10});
s4.printReverse();
cout << "Display the reverse elements of the stack:" << endl;
s4.print();
return 0;
}
|