-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
79 lines (78 loc) · 1.69 KB
/
Copy pathstack.cpp
File metadata and controls
79 lines (78 loc) · 1.69 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
#include "stack.h"
#include <iostream>
using namespace std;
//Implementation of StackArray
StackArray::StackArray(int size) {
capacity = size;
arr = new int[capacity];
top = -1;
}
StackArray::~StackArray() {
delete[] arr;
}
bool StackArray::isEmpty() {
return top == -1;
}
bool StackArray::isFull() {
return top == capacity - 1;
}
void StackArray::push(int value) {
if (isFull()) {
cout << "Stack Overflow! Cannot push " << value << endl;
return;
}
arr[++top] = value;
cout << value << " pushed to stack" << endl;
}
int StackArray::pop() {
if (isEmpty()) {
cout << "Stack Underflow! Stack is empty" << endl;
return -1;
}
return arr[top--];
}
int StackArray::peek() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return -1;
}
return arr[top];
}
//Implementation of StackLinkedList
StackLinkedList::StackLinkedList() {
top = nullptr;
}
StackLinkedList::~StackLinkedList() {
while (!isEmpty()) {
pop();
}
}
bool StackLinkedList::isEmpty() {
return top == nullptr;
}
void StackLinkedList::push(int value) {
Node* newNode = new Node(value,top);
newNode->data = value;
newNode->next = top;
top = newNode;
cout << value << " pushed to stack" << endl;
}
int StackLinkedList::pop() {
if (isEmpty()) {
cout << "Stack Underflow! Stack is empty" << endl;
return -1;
}
Node* temp = top;
int val = temp->data;
top = top->next;
delete temp;
return val;
}
int StackLinkedList::peek() {
if (isEmpty()) {
cout << "Stack is empty!" << endl;
return -1;
}
cout << "Value peeked" << endl;
return top->data;
}