stack.h
#ifndef STACK_H
#define STACK_H
#include <iostream>
using namespace std;
class Stack {
private:
int* arr;
int top;
int capacity; // 容量
public:
Stack(int size); // 构造
~Stack(); // 析构
Stack(const Stack& other); // 复制构造函数
Stack& operator=(const Stack& other); // 赋值
int peekFirst(); // 访问第一个元素
int peekLast(); // 访问最后一个元素
int getCapacity(); // 返回容量
bool isEmpty(); // 判空
void push(int x); // 入栈
int pop(); // 出栈
};
#endif // STACK_H
stack.cpp
#include "stack.h"
// 有参构造
Stack::Stack(int size) : top(-1), capacity(size)
{
arr = new int[size];
}
// 复制构造函数
Stack::Stack(const Stack& other) : top(other.top), capacity(other.capacity)
{
arr = new int[capacity];
for (int i = 0; i <= top; ++i)
{
arr[i] = other.arr[i];
}
}
// 赋值重载
Stack& Stack::operator=(const Stack& other)
{
if (this != &other)
{
delete[] arr;
top = other.top;
capacity = other.capacity;
arr = new int[capacity];
for (int i = 0; i <= top; ++i)
{
arr[i] = other.arr[i];
}
}
return *this;
}
// 访问第一个元素
int Stack::peekFirst()
{
if (isEmpty()) {
std::cout << "栈为空\n";
return -1;
}
return arr[0];
}
// 访问最后一个元素
int Stack::peekLast()
{
if (isEmpty())
{
std::cout << "栈为空\n";
return -1;
}
return arr[top];
}
// 返回容量
int Stack::getCapacity()
{
return capacity;
}
// 判空
bool Stack::isEmpty()
{
return top == -1; // 栈空
}
// 入栈
void Stack::push(int x)
{
if (top == capacity - 1)
{
std::cout << "栈溢出\n";
return;
}
arr[++top] = x;
}
// 出栈
int Stack::pop()
{
if (isEmpty())
{
std::cout << "栈为空\n";
return -1;
}
return arr[top--];
}
// 析构函数
Stack::~Stack()
{
delete[] arr;
}
queue.h
// queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
using namespace std;
class Queue {
private:
int* arr; // 存储队列元素的数组
int front; // 队头索引
int rear; // 队尾索引
int capacity; // 队列容量
public:
Queue(int size);
void push(int x);
int pop();
Queue & operator=(const Queue& other);
int frontnum();
int back();
bool empty();
int size();
void swap(Queue& other);
~Queue();
};
#endif // QUEUE_H
queue.cpp
#include "queue.h"
Queue::Queue(int size) : front(0), rear(0), capacity(size)
{
arr = new int[size]; //初始化大小为size
}
void Queue::push(int x)
{
if (rear == capacity)
{
std::cout << "队列满\n";
return;
}
arr[rear++] = x; //尾插
}
int Queue::pop()
{
if (empty())
{
std::cout << "队列为空\n";
return -1;
}
return arr[front++];
}
Queue& Queue::operator=(const Queue& other)
{
if (this != &other)
{
delete[] arr;
front = other.front;
rear = other.rear;
capacity = other.capacity;
arr = new int[capacity];
for (int i = front; i <= rear; ++i)
{
arr[i] = other.arr[i];
}
}
return *this;
}
int Queue::frontnum()
{
if (empty())
{
std::cout << "队列为空\n";
return -1;
}
return arr[front];
}
int Queue::back()
{
if (empty())
{
std::cout << "队列为空\n";
return -1;
}
return arr[rear - 1];
}
bool Queue::empty()
{
return front == rear; // 判空
}
int Queue::size()
{
return rear - front; // 返回容量
}
void Queue::swap(Queue& other)
{
std::swap(arr, other.arr);
std::swap(front, other.front);
std::swap(rear, other.rear);
std::swap(capacity, other.capacity);
}
Queue::~Queue()
{
delete[] arr;
}