Skip to content

Instantly share code, notes, and snippets.

@keir-nellyer
Created April 16, 2017 17:37
Show Gist options
  • Save keir-nellyer/3afa6e55e6eeebc2eb983e37671060c4 to your computer and use it in GitHub Desktop.
Save keir-nellyer/3afa6e55e6eeebc2eb983e37671060c4 to your computer and use it in GitHub Desktop.
#include "stack.h"
#include <vector>
class ArrayStack: public StackADT {
public:
ArrayStack(int size): stackSize(size), data(new int[stackSize]) {};
bool isEmpty() {
return top == 0;
}
bool isFull() {
return top == stackSize;
}
void push(int x) {
data[top++] = x;
}
int pop() {
int x = data[--top];
data[top] = 0;
return x;
}
int size() {
return top;
}
std::vector<int> getContents() {
std::vector<int> contents;
for (int i = 0; i < top; i++) {
int value = data[i];
contents.push_back(value);
}
return contents;
}
protected:
int stackSize;
int top = 0;
int* data;
};
#include "stack.h"
#include <vector>
class LinkedListStack: public StackADT {
public:
bool isEmpty() {
return head->next == NULL;
}
bool isFull() {
try {
new Node;
} catch (std::bad_alloc&) {
return true;
}
return false;
}
void push(int x) {
Node * node = new Node;
node->value = x;
node->next = head;
head = node;
}
int pop() {
Node * node = head;
int lastValue = head->value;
head = head->next;
return lastValue;
}
int size() {
int size = 0;
Node *node = head;
while (node != tail) {
size++;
node = node->next;
}
return size;
}
std::vector<int> getContents() {
std::vector<int> data;
Node *node = head;
while (node != tail) {
data.push_back(node->value);
node = node->next;
}
return data;
}
private:
struct Node {
int value;
Node *next = NULL;
};
Node * head = new Node;
Node * tail = head;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment