当前位置: 首页> 房产> 建筑 > C++使用MyStack和MyQueue封装栈和队列

C++使用MyStack和MyQueue封装栈和队列

时间:2025/7/9 20:42:52来源:https://blog.csdn.net/sjrhsk_hahaha/article/details/141873282 浏览次数:0次

封装栈的构造,复制,判空判满,入栈出栈等函数

// 使用MySstack实现栈#include <iostream>
using namespace std;class MyStack
{
private:int Top;  // 栈顶位置int Size; // 栈大小int *Arr; // 数组指针public:MyStack() { cout << "默认构造" << endl; }MyStack(int size) : Size(size), Top(-1){Arr = new int[size];cout << "参数构造" << endl;}~MyStack() { cout << "析构" << endl; }// 深拷贝赋值运算符重载MyStack &operator=(const MyStack &src){delete[] Arr; // 删除原数组Top = src.Top;Size = src.Size;Arr = new int[Size];// 复制数组for (int i = 0; i <= Top; i++){Arr[i] = src.Arr[i];}return *this;}// 获取栈顶元素int top(){return Arr[Top];}// 判断是否为空bool empty(){return Top == -1;}// 获取栈大小int size(){return Top + 1;}// 入栈int push(int val){if (Top == Size - 1){cout << "栈满" << endl;return -1;}Arr[++Top] = val;return 0;}// 出栈int pop(){if (empty()){cout << "栈空" << endl;return (-1);}return Arr[Top--];}
};
int main()
{MyStack s1(10);if (s1.empty())cout << "栈空" << endl;s1.push(1);s1.push(2);s1.push(3);MyStack s2 = s1;cout << s2.pop() << endl;cout << s2.pop() << endl;cout << s2.pop() << endl;cout << s2.pop() << endl; // 栈空return 0;
}

封装队列的构造,赋值,判空判满,入队出队函数

#include <iostream>
using namespace std;class Queue
{
private:int Front; // 队头的位置int Rear;  // 队尾的位置int Size;  // 队列的大小int *Que;  // 队列本体 public:// 构造函数Queue(int size){Size = size;Front = Rear = 0;Que = new int[Size];cout << "有参构造" << endl;}// 析构函数~Queue(){delete[] Que;}// empty 判断队列是否为空bool empty(){return Front == Rear;}// full 判断队列是否已满bool full(){return (Rear + 1) % Size == Front;}// front 访问第一个元素int front(){if (empty()){cout << "队列为空" << endl;return -1;}return Que[Front];}//= 重载赋值函数Queue &operator=(const Queue &src){if (this != &src){delete[] Que; // 释放原有内存Size = src.Size;Front = src.Front;Rear = src.Rear;Que = new int[src.Size]; // 分配新的内存for (int i = src.Front; i != src.Rear; i = (i + 1) % Size){Que[i] = src.Que[i];}}return *this;}// back 访问最后一个元素int back(){if (empty()){cout << "队列为空" << endl;return -1;}return Que[Rear];}// size 返回容纳元素数int size(){return (Rear - Front + Size) % Size;}// push 入队int push(int x){if (full()){cout << "队列已满" << endl;return -1;}Que[Rear] = x;Rear = (Rear + 1) % Size;return x;}// pop 出队int pop(){if (empty()){cout << "队列为空" << endl;return -1;}int result = Que[Front];Front = (Front + 1) % Size;return result;}
};int main()
{Queue q1(5);q1.push(1);q1.push(2);q1.push(3);q1.push(4);Queue q2 = q1;cout << q2.pop() << endl;q2.push(5);for (int i = 0; i < 5; i++){cout << q2.pop() << endl; // 最后队列为空}
}

关键字:C++使用MyStack和MyQueue封装栈和队列

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: