-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStacksUsingLinkedList.cpp
120 lines (96 loc) · 2.32 KB
/
StacksUsingLinkedList.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
/*******
Following Node class and main already created internally. You can directly use that.
#include<iostream>
using namespace std;
template <typename T>
class Node {
public :
T data;
Node<T> *next;
Node(T data) {
this -> data = data;
next = NULL;
}
};
#include "Stack.h"
int main() {
Stack<int> st;
int choice;
cin >> choice;
int input;
while (choice !=-1) {
if(choice == 1) {
cin >> input;
st.push(input);
}
else if(choice == 2) {
int ans = st.pop();
if(ans != 0) {
cout << ans << endl;
}
else {
cout << "-1" << endl;
}
}
else if(choice == 3) {
int ans = st.top();
if(ans != 0) {
cout << ans << endl;
}
else {
cout << "-1" << endl;
}
}
else if(choice == 4) {
cout << st.getSize() << endl;
}
else if(choice == 5) {
cout << st.isEmpty() << endl;
}
cin >> choice;
}
}
***********/
template <typename T>
class Stack {
Node<T> *head;
int size; // number of elements prsent in stack
public :
Stack() {
head=NULL ;
size=0 ;
}
int getSize() {
return size ;
}
bool isEmpty() {
return size==0 ;
}
void push(T element) {
Node<T> *newnode = new Node<T>(element);
newnode->next=head ;
head=newnode ;
size++ ;
}
T pop() {
// Return 0 if stack is empty. Don't display any other message
if(isEmpty()){
return 0 ;
}else{
T ans = head->data ;
Node<T> *temp=head ;
head=head->next ;
delete temp ;
size-- ;
return ans ;
}
}
T top() {
// Return 0 if stack is empty. Don't display any other message
if(isEmpty()){
return 0 ;
}else{
return head->data ;
}
}
};