-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackList.cpp
More file actions
97 lines (80 loc) · 1.98 KB
/
StackList.cpp
File metadata and controls
97 lines (80 loc) · 1.98 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
87
88
89
90
91
92
93
94
95
96
97
// C++ code
#include <iostream>
class StackList;
class StackNode{
private:
int data;
StackNode *next;
public:
StackNode():data(0){
next = 0;
}
StackNode(int x):data(x){
next = 0;
}
StackNode(int x, StackNode *nextNode):data(x),next(nextNode){};
friend class StackList;
};
class StackList{
private:
StackNode *top; // remember the address of top element
int size; // number of elements in Stack
public:
StackList():size(0),top(0){};
void Push(int x);
void Pop();
bool IsEmpty();
int Top();
int getSize();
};
void StackList::Push(int x){
if (IsEmpty()) {
top = new StackNode(x);
size++;
return;
}
StackNode *newnode = new StackNode(x); // Push_front() in Linked list
newnode->next = top;
// StackNode *newnode = new StackNode(x,top);
top = newnode;
size++;
}
void StackList::Pop(){
if (IsEmpty()) {
std::cout << "Stack is empty.\n";
return;
}
StackNode *deletenode = top;
top = top->next;
delete deletenode;
deletenode = 0;
size--;
}
bool StackList::IsEmpty(){
return (size == 0); // if size==0, return true
}
int StackList::Top(){
if (IsEmpty()) {
std::cout << "Stack is empty.\n";
return -1;
}
return top->data;
}
int StackList::getSize(){
return size;
}
int main(){
StackList s;
s.Pop();
s.Push(32);
s.Push(4);
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
s.Push(15);
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
s.Pop();
s.Pop();
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
s.Pop();
std::cout << "\ntop: " << s.Top() << "\nsize: " << s.getSize() << std::endl;
return 0;
}