-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.cpp
93 lines (73 loc) · 1.48 KB
/
Stack.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
92
93
#include <iostream>
using namespace std;
struct Node
{
int data;
struct Node* next = nullptr;
};
class Stack
{
struct Node* top = nullptr;
public:
bool isEmpty() const
{
return (top == nullptr);
}
int peek() const
{
return top->data; // no exception handling done here (top could be nullptr)
}
void push(int d)
{
Node* temp = new Node;
temp->data = d;
temp->next = top;
top = temp;
}
void pop()
{
if(!isEmpty())
{
cout << "Removing " << top->data << " from stack" << endl;
Node* temp = top->next;
delete top;
top = temp;
}
}
void print() const
{
Node* temp = top;
while(temp != nullptr)
{
cout << temp->data << endl;
temp = temp->next;
}
}
~Stack()
{
while(top != nullptr)
{
cout << "Deleting " << top->data << " from stack" << endl;
Node* temp = top->next;
delete top;
top = temp;
}
}
};
int main()
{
Stack* stackObj = new Stack();
stackObj->push(1);
stackObj->push(2);
stackObj->push(3);
stackObj->push(4);
stackObj->push(5);
stackObj->push(6);
stackObj->print();
stackObj->pop();
stackObj->print();
cout << "Peeked value is " << stackObj->peek() << endl;
delete stackObj;
stackObj = nullptr;
return 0;
}