作业:
将之前实现的顺序表、栈、队列都更改成模板类
Stack
#include <iostream>
using namespace std;template <typename T>
class Stack {
private:
T* arr; // 存储栈元素的数组
int top; // 栈顶索引
int capacity; // 栈的容量public:
Stack(int size) {
arr = new T[size];
capacity = size;
top = -1; // 初始化栈顶索引
}~Stack() {
delete[] arr; // 释放内存
}void push(T x) {
if (top == capacity - 1) {
cout << "栈溢出" << endl;
return;
}
arr[++top] = x;
}void pop() {
if (top == -1) {
cout << "栈为空" << endl;
return;
}
top--;
}T peek() {
if (top == -1) {
cout << "栈为空" << endl;
return T(); // 返回默认值
}
return arr[top]; // 返回栈顶元素
}bool isEmpty() {
return top == -1; // 检查栈是否为空
}int size() {
return top + 1; // 返回栈的大小
}
};int main() {
Stack<int> stack(5); // 使用模板类
stack.push(10);
stack.push(20);
cout << "栈顶元素: " << stack.peek() << endl;
stack.pop();
cout << "栈顶元素: " << stack.peek() << endl;
return 0;
}
Queue
#include <iostream>
using namespace std;template <typename T>
class Queue {
private:
T* arr; // 存储队列元素的数组
int front;
int rear;
int capacity; // 队列的容量public:
Queue(int size) {
arr = new T[size];
capacity = size;
front = 0;
rear = -1;
}~Queue() {
delete[] arr; // 释放内存
}void push(T x) {
if (rear == capacity - 1) {
cout << "队列溢出" << endl;
return;
}
arr[++rear] = x; // 将元素插入队列
}void pop() {
if (front > rear) {
cout << "队列为空" << endl;
return;
}
front++;
}T frontElement() {
if (front > rear) {
cout << "队列为空" << endl;
return T(); // 返回默认值
}
return arr[front];
}bool isEmpty() {
return front > rear; // 检查队列是否为空
}int size() {
return rear - front + 1; // 返回队列的大小
}
};int main() {
Queue<int> queue(5); // 使用模板类
queue.push(10);
queue.push(20);
cout << "队列前端元素: " << queue.frontElement() << endl;
queue.pop();
cout << "队列前端元素: " << queue.frontElement() << endl;
return 0;
}