-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.cpp
More file actions
86 lines (83 loc) · 1.39 KB
/
Stack.cpp
File metadata and controls
86 lines (83 loc) · 1.39 KB
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
#include <iostream>
using namespace std;
template <typename T>
struct Node {
T data;
Node<T>* ptr;
Node(T data = 0):data(data),ptr(NULL) {}
};
template <typename T>
class Stack {
private:
size_t size;
Node<T>* top;
public:
Stack() :size(0), top(nullptr) {};
void Push(T data) {
Node<T>* new_node = new Node<T>(data);
new_node->ptr = top;
top = new_node;
size++;
}
void Print() {
if (top == NULL) {
cout << "Stack is empty !";
}
Node<T>* temp = top;
while (temp != NULL) {
cout << temp->data << endl;
temp = temp->ptr;
}
cout << endl;
}
void Pop() {
if (top == NULL) {
cout << "Stack is empty !";
return;
}
Node<T>* temp = top;
top = top->ptr;
delete temp;
}
T getData() {
return top->data;
}
bool isEmpty() {
return size == 0;
}
~Stack() {
Node<T>* temp = top;
while (temp != NULL){
delete temp;
temp = temp->ptr;
}
}
Stack(const Stack& obj) {
size = obj.size;
if (size == 0) {
return;
}
Node<T>* temp = obj.top;
top = new Node<T>(temp->data);
Node<T>* temp_this = top;
temp = temp->ptr;
while (temp != NULL) {
temp_this->ptr = new Node<T>(temp->data);
temp = temp->ptr;
temp_this = temp_this->ptr;
}
}
};
int main() {
Stack<int> stack;
stack.Push(3);
stack.Push(5);
stack.Push(7);
Stack<int> stack2 = stack;
stack.Print();
stack.Pop();
stack.Push(10);
stack.Print();
stack2.Print();
return 0;
}