sqStack.cpp
#include <iostream>
#include "Stack.h"
using namespace std;
int main() {
BothStack<char> s1(5);
try{
s1.push(1,'a');
s1.push(1,'b');
// s1.push(1,'c');
cout << s1.pop(1)<<endl;
cout << s1.pop(2)<<endl;
}
catch (BothStack<char>::Full) {
cout << "full"<<endl;
}
catch (BothStack<char>::Empty1) {
cout << "empty1"<<endl;
}
catch (BothStack<char>::Empty2) {
cout << "empty2"<<endl;
}
return 0;
}
Stack.cpp
#include <iostream>
#include "Stack.h"
// 构造函数,分配最大内存空间
template<class T>
BothStack<T>::BothStack() {
size = MAX_SIZE;
top1 = -1;
data = new T[size];
top2 = size;
};
template<class T>
BothStack<T>::BothStack(int s) {
if (MAX_SIZE > size) {
size = s;
top1 = -1;
top2 = size;
data = new T[size];
} else {
cout << "栈最大容量为:" << MAX_SIZE << endl;
size = MAX_SIZE;
data = new T[size];
top1 = -1;
top2 = size;
}
}
//析构函数
template<class T>
BothStack<T>::~BothStack() {
delete[] data;
}
//入栈
template<class T>
void BothStack<T>::push(int num, T x) {
if (isFull(1)) {
throw Full();
}
if (isFull(2)) {
throw Full();
} else {
switch (num) {
case 1:
data[++top1] = x; //先top+1,再放入数据
break;
case 2:
data[--top2] = x; //先top-1,再放入数据
default:
break;
}
}
}
//出栈
template<class T>
T BothStack<T>::pop(int num) {
switch (num) {
case 1:
if (isEmpty(1)) {
throw Empty1();
} else {
return data[top1--];//先弹出数据,再top-1
}
case 2:
if (isEmpty(2)) {
throw Empty2();
} else {
return data[top2--];//先弹出数据,再top-1
}
default:
break;
}
}
//获取栈顶元素,不弹出,不改变数值
template<class T>
T BothStack<T>::getTop(int num) {
if (isEmpty(num)) {
switch (num) {
case 1:
throw Empty1();
case 2:
throw Empty2();
}
} else {
switch (num) {
case 1:
return data[top1];
case 2:
return data[top2];
default:
break;
}
}
}
template<class T>
bool BothStack<T>::isEmpty(int num) {
switch (num) {
case 1:
if (top1 == -1) return true;
else return false;
case 2:
if (top2 == size) return true;
else return false;
default:
break;
}
}
template<class T>
bool BothStack<T>::isFull(int num) {
if (top1 + 1 == top2) return true;
else return false;
}
template
class BothStack<char>; //类模板分文件必须加这一句
Stack.h
//
// Created by 63400 on 2021/10/30.
//
#ifndef HOMEWORK_STACK_H
#define HOMEWORK_STACK_H
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
template<class T>
class BothStack {
private:
T * data; //指向数组的指针
int size; //数组的大小
int top1,top2; //栈顶
public:
BothStack();
BothStack(int );
~BothStack();
void push(int num,T x); //压栈,num = 1代表栈1,num = 2代表栈2
T pop(int num); //出栈并返回出栈元素
T getTop(int num); //获取栈顶元素
bool isEmpty(int num); //判断栈是否为空
bool isFull(int num); //判断栈是否为满
class Full{};
class Empty1{};
class Empty2{};
};
typedef BothStack<char> CharBothStack;
#endif //HOMEWORK_STACK_H
我后悔,为什么大二没有开始学习。
现在开始,会不会晚了呢?
别想这么多了,加油啊!