数组和链表实现栈
#include <iostream>
using namespace std;
class Stack {
public:
virtual bool push(int value) = 0;
virtual bool pop(int &value) = 0;
virtual bool isEmpty() = 0;
virtual int size() = 0;
};
class ArrayStack : public Stack {
int *data;
int top, capcity;
bool isFull() {
return top == capcity;
}
public:
ArrayStack(int capcity) : top(0), capcity(capcity) {
data = new int[capcity];
}
~ArrayStack() {
delete[] data;
}
ArrayStack(const ArrayStack&) = delete;
ArrayStack& operator=(const ArrayStack&) = delete;
bool push(int value) override {
if (isFull())
return false;
data[top++] = value;
return true;
}
bool pop(int &value) override {
if (isEmpty())
return false;
value = data[--top];
return true;
}
bool isEmpty() override {
return top == 0;
}
int size() override {
return top;
}
};
class Node {
public:
int value;
Node *next;
};
class ListStack : public Stack {
Node *head;
int count;
public:
ListStack() : count(0), head(nullptr) {}
~ListStack() {
while (head) {
Node *cur = head;
head = head->next;
delete cur;
}
}
ListStack(const ListStack&) = delete;
ListStack& operator=(const ListStack&) = delete;
bool push(int value) override {
Node *oldHead = head;
head = new Node;
head->value = value;
head->next = oldHead;
++count;
return true;
}
bool pop(int &value) override {
if (isEmpty())
return false;
Node *cur = head;
value = cur->value;
head = cur->next;
delete cur;
--count;
return true;
}
bool isEmpty() override {
return head == nullptr;
}
int size() override {
return count;
}
};
bool test(Stack *stack, const int len) {
int a[len];
for (int i = 0; i < len; ++i)
a[i] = i;
if (!stack->isEmpty()) {
cout << __LINE__ << " stack should empty" << endl;
return false;
}
for (int i = 0; i < len; ++i) {
if (!stack->push(a[i])) {
cout << __LINE__ << " stack push failed" << endl;
return false;
}
if (stack->size() != i + 1) {
cout << __LINE__ << " size = " << stack->size() << ", but expect " << i + 1 << endl;
return false;
}
}
int value;
for (int i = 0; i < len; ++i) {
if (!stack->pop(value)) {
cout << __LINE__ << " stack pop failed" << endl;
return false;
}
if (value + i != len - 1) {
cout << __LINE__ << " value = " << value << ", but expect " << len - i - 1 << endl;
return false;
}
if (stack->size() + i + 1 != len) {
cout << __LINE__ << " size = " << stack->size() << ", but expect " << len - i - 1 << endl;
return false;
}
}
if (stack->pop(value)) {
cout << __LINE__ << " empty stack should pop failed" << endl;
return false;
}
return true;
}
int main() {
ArrayStack arrayStack(10);
ListStack listStack;
cout << boolalpha << test(&arrayStack, 7) << endl;
cout << boolalpha << test(&listStack, 7) << endl;
return 0;
}