参考:https://blog.csdn.net/LKJgdut/article/details/105189461
C++代码如下
Stack
Stack.h
template<typename T>
class Stack {
public:
virtual int getSize() = 0;
virtual bool isEmpty() = 0;
virtual void push(T e) = 0;
virtual T pop() = 0;
virtual T peek() = 0;
};
ArrayStack.h
#include "Array.h"
#include "Stack.h"
template<typename T>
class ArrayStack : public Stack<T> {
/*
注意,我们是基于前面的动态数组来创建我们的栈的,因此我们初始化栈的时候,必须先初始化一个动态数组。
*/
private:
Array<T> *array;
public:
ArrayStack(int capacity) {
array = new Array<T>(capacity);
}
ArrayStack() {
array = new Array<T>();
}
~ArrayStack() {
delete[] array;
array = nullptr;
}
int getSize() {
return array->getSize();
}
T pop() {
return array->removeLast();
}
T peek() {
return array->getLast();
}
void push(T e) {
array->addLast(e);
}
bool isEmpty() {
return array->isEmpty();
}
/**
* 打印数组的所有元素
*/
void print() {
std::cout << "ArrayStack: size = " << array->getSize() << ", capacity = " << array->getCapacity() << std::endl;
std::cout << "bottom ";
array->print();
std::cout << " top" << std::endl;
}
};
栈的一个应用——括号匹配
#include <stack>
#include <string>
class Solution {
public:
bool isValid(std::string s) {
//先创建一个栈,注意这个栈存储的是char类型的字符数据
std::stack<char> *stack = new std::stack<char>();
for (int i = 0; i < s.size(); ++i) {
char c = s.at(i);
if (c == '(' || c == '[' || c == '{') {
stack->push(c);
} else {//如果读取到的是右括号,首先判断栈是否为空,为空说明字符串无效
if (stack->empty()) {
return false;
}
char topChar = stack->top();
if (c == ')' && topChar != '(') {
return false;
}
if (c == ']' && topChar != '[') {
return false;
}
if (c == '}' && topChar != '{') {
return false;
}
stack->pop();//注意判断完一组要pop出来
}
}
return stack->empty();//注意是bool型的
}
};
Queue
同样,我们没有获取队列中任意角标元素的方法:get(index),因为对于队列这种数据结构,只能看到队首的元素,而无法获取队列中的某个元素。当然,队列也无法实现将元素插入队列中某任意位置:add(int index , E e),或者删除队列中任意位置的元素:remove(int index)。
既对于队列来说,我们只能往队尾( enqueue(E) )添加元素,从队首( dequeue() )移除元素,或者获取队首获取元素( getFront() ),其他位置的操作不能实现。
Queue.h
template<typename T>
class Queue {
public:
virtual int getSize() = 0;
virtual bool isEmpty() = 0;
virtual void enqueue(T e) = 0;
virtual T dequeue() = 0;
virtual T getFront() = 0;
};
ArrayQueue.h
#include "Queue.h"
#include "Array.h"
template<class T>
class ArrayQueue : public Queue<T> {
public:
ArrayQueue() {
array = new Array<T>(10);
}
ArrayQueue(int capacity) {
array = new Array<T>(capacity);
}
~ArrayQueue() {
delete[] array;
array = nullptr;
}
int getSize() {
return array->getSize();
}
T dequeue() {
return array->removeFirst();
}
T getFront() {
return array->getFirst();
}
void enqueue(T e) {
array->addLast(e);
}
bool isEmpty() {
return array->isEmpty();
}
/**
* 打印数组的所有元素
*/
void print() {
std::cout << "ArrayQueue: size = " << array->getSize() << ", capacity = " << array->getCapacity() << std::endl;
std::cout << "front ";
array->print();
std::cout << " tail" << std::endl;
}
private:
Array<T> *array;
};
LoopQueue