本文主要是介绍C++使用MyStack和MyQueue封装栈和队列,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
封装栈的构造,复制,判空判满,入栈出栈等函数
// 使用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封装栈和队列的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!