-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement stack using linked list.cpp
64 lines (63 loc) · 1.28 KB
/
Implement stack using linked list.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
#include<iostream>
using namespace std;
struct stackNode {
int data;
stackNode * next;
int size;
stackNode(int d) {
data = d;
next = NULL;
}
};
struct stack {
stackNode * top;
int size;
stack() {
top = NULL;
size = 0;
}
void stackPush(int x) {
stackNode * element = new stackNode(x);
element -> next = top;
top = element;
cout << "Element pushed" << "\n";
size++;
}
int stackPop() {
if (top == NULL) {
return -1;
}
int topData = top -> data;
stackNode * temp = top;
top = top -> next;
delete temp;
size--;
return topData;
}
int stackSize() {
return size;
}
bool stackIsEmpty() {
return top == NULL;
}
int stackPeek() {
if (top == NULL) return -1;
return top -> data;
}
void printStack() {
stackNode * current = top;
while (current != NULL) {
cout << current -> data << " ";
current = current -> next;
}
}
};
int main() {
stack s;
s.stackPush(10);
cout << "Element popped: " << s.stackPop() << "\n";
cout << "Stack size: " << s.stackSize() << "\n";
cout <<"Stack empty or not? "<<s.stackIsEmpty()<<"\n";
cout << "stack's top element: " << s.stackPeek() << "\n";
return 0;
}