forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linklist.c++
70 lines (58 loc) · 1.47 KB
/
linklist.c++
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
#include <iostream>
class Node {
public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};
class Stack {
private:
Node* top;
public:
Stack() {
top = nullptr;
}
void push(int data) {
Node* newNode = new Node(data);
if (top == nullptr) {
top = newNode;
} else {
newNode->next = top;
top = newNode;
}
}
int pop() {
if (isEmpty()) {
std::cerr << "Stack is empty." << std::endl;
return -1; // You can return a different value or throw an exception as per your requirements.
}
int data = top->data;
Node* temp = top;
top = top->next;
delete temp;
return data;
}
int peek() {
if (isEmpty()) {
std::cerr << "Stack is empty." << std::endl;
return -1; // You can return a different value or throw an exception as per your requirements.
}
return top->data;
}
bool isEmpty() {
return top == nullptr;
}
};
int main() {
Stack myStack;
myStack.push(1);
myStack.push(2);
myStack.push(3);
std::cout << "Top element: " << myStack.peek() << std::endl; // Output: 3
std::cout << "Popped element: " << myStack.pop() << std::endl; // Output: 3
std::cout << "Is the stack empty? " << (myStack.isEmpty() ? "Yes" : "No") << std::endl; // Output: No
return 0;
}