-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
52 lines (46 loc) · 1.14 KB
/
stack.cpp
File metadata and controls
52 lines (46 loc) · 1.14 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
#include <iostream>
#include "stack.h"
// Constructor initializes an empty stack
Stack::Stack() : top(nullptr) {}
// Add element to the top of the stack
bool Stack::push(const int data) {
Node* newNode = new (std::nothrow) Node(data);
if (!newNode) {
return false;
}
newNode->next = top;
top = newNode;
return true;
}
// Remove and return the top element of the stack
int Stack::pop(bool &success) {
if (isEmpty()) {
success = false;
return 0;
}
Node* temp = top;
int val = temp->data;
top = top->next;
delete temp;
success = true;
return val;
}
// Returns true if the stack is empty
bool Stack::isEmpty() const {
return top == nullptr;
}
// Return the top element of the stack without removing it
int Stack::peek(bool& success) const {
if (isEmpty()) {
success = false;
return 0;
}
success = true;
return top->data;
}
// Destructor to free the allocated memory
Stack::~Stack() {
while (!isEmpty()) {
pop(); // Pop all elements to free memory
}
}