-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacklinkedlist.cpp
58 lines (46 loc) · 1.22 KB
/
stacklinkedlist.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
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define _z ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
struct Node{
int data;
Node* next;
};
class Stack{
private:
Node* top;
public:
Stack() : top{nullptr} {};
void push(int d){
Node* newNode = new Node{d, nullptr};
newNode -> next = top;
top = newNode;
}
bool isEmpty(){
return top == nullptr;
}
int pop(){
if(isEmpty()){
cout<<"Stack is empty"<<endl;
return -1;
}
int value = top->data;
Node* poppedtop = top;
top = top -> next;
delete top;
return value;
}
};
int main(){
Stack stack;
stack.push(1);
stack.push(2);
stack.push(3);
// Pop the values off the stack and print them
cout << stack.pop() <<endl; // Output: 3
cout << stack.pop() <<endl; // Output: 2
cout << stack.pop() <<endl; // Output: 1
// Try to pop from an empty stack (should print an error message)
cout << stack.pop() <<endl;
return 0;
}