-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStack.cpp
More file actions
85 lines (74 loc) · 1.81 KB
/
Copy pathStack.cpp
File metadata and controls
85 lines (74 loc) · 1.81 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
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
#include "Stack.h"
#include <iostream>
// ===== Member 2: StackArray ================================================
// Implement StackArray methods in this section.
StackArray::StackArray(int capacity) {
this->capacity = capacity;
this->arr = new int[capacity];
this->topIndex = -1;
}
StackArray::~StackArray() {
delete[] arr;
}
void StackArray::push(int value) {
if (isFull()) {
std::cout << "Stack Overflow\n";
return;
}
arr[++topIndex] = value;
}
int StackArray::pop() {
if (isEmpty()) {
std::cout << "Stack Underflow\n";
return -1;
}
return arr[topIndex--];
}
int StackArray::peek() const {
if (isEmpty()) {
std::cout << "Stack is empty\n";
return -1;
}
return arr[topIndex];
}
bool StackArray::isEmpty() const {
return topIndex == -1;
}
bool StackArray::isFull() const {
return topIndex == capacity - 1;
}
// ===== Member 3: StackLinkedList ===========================================
// Implement StackLinkedList methods in this section.
#include <stdexcept>
StackLinkedList::StackLinkedList() {
top = nullptr;
};
bool StackLinkedList::isEmpty()const{
return top==nullptr;
};
void StackLinkedList::push(int value) {
Node* newNode = new Node(value);
newNode->next = top;
top = newNode;
};
int StackLinkedList::pop(){
if(isEmpty()){
throw std::runtime_error("Stack underflow: Cannot pop from an empty stack.");
};
Node* temp = top;
int value = temp->data;
top = top->next;
delete temp;
return value;
};
int StackLinkedList::peek() const {
if(isEmpty()){
throw std::runtime_error("Stack underflow: Cannot peek from an empty stack.");
};
return top->data;
};
StackLinkedList::~StackLinkedList() {
while (!isEmpty()) {
pop();
};
};