Skip to content

Instantly share code, notes, and snippets.

@m-primo
Created April 25, 2020 14:03
Show Gist options
  • Save m-primo/ca01ee89702719e8420b876dce14642e to your computer and use it in GitHub Desktop.
Save m-primo/ca01ee89702719e8420b876dce14642e to your computer and use it in GitHub Desktop.
Simple Stack Implementation in C++
#include <iostream>
using namespace std;
#define null 0
class StackArray {
private:
int size;
int *stackArr;
int top;
void resize() {
int tempSize = size * 2;
int *temp = new int[tempSize];
for(int i = 0; i < size; i++) temp[i] = stackArr[i];
delete[] stackArr;
stackArr = temp;
size = tempSize;
}
public:
StackArray(int size) {
this->size = size;
stackArr = new int[size];
top = -1;
}
void push(int data) {
if(top == size - 1) resize();
stackArr[++top] = data;
}
void pop() {
if(top != -1) top--;
}
void print() {
for(int i = 0; i <= top; i++) {
cout << stackArr[(top - i) % size] << endl;
}
cout << endl;
}
void test() {
push(1);
push(3);
push(4);
push(7);
print();
pop();
print();
}
~StackArray() {
delete[] stackArr;
}
};
class Node {
public:
int data;
Node *next;
Node(int data) {
this->data = data;
next = null;
}
};
class StackLinkedList {
private:
Node *top;
public:
StackLinkedList() {
top = null;
}
void push(int data) {
Node *n = new Node(data);
if(top == null) top = n;
else {
n->next = top;
top = n;
}
}
void pop() {
if(top != null) {
Node *temp = top;
top = top->next;
delete(temp);
}
}
void print() {
Node *temp = top;
while(temp != null) {
cout << temp->data << endl;
temp = temp->next;
}
cout << endl;
}
void test() {
push(3);
push(9);
push(6);
print();
pop();
print();
}
~StackLinkedList() {
Node *next;
while(top != null) {
next = top->next;
delete(top);
top = next;
}
}
};
int main() {
cout << endl << "Array:" << endl;
StackArray sArr(4);
sArr.test();
cout << endl << "Linked List:" << endl;
StackLinkedList sll;
sll.test();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment