手动实现队列
代码如下
MyQueue.h
#ifndef MYQUEUE_H
#define MYQUEUE_H
#include <iostream>
#include <cstring>
using namespace std;
class Queue{
private:
char* data;
int len;
int size;
int front;
int rear;
public:
Queue();
Queue(const char* d, int size);
~Queue();
Queue (const Queue &other);
Queue& operator= (const Queue &other);
char MyFront();
char back();
bool empty();
int MySize();
void push(char e);
void emplace(char e);
char pop();
void swap(Queue &other);
};
#endif
MyQueue.cpp
#include "MyQueue.h"
Queue::Queue():len(0),size(20),front(0),rear(0){
data = new char[size];
data[0] = '\0';
};
Queue::Queue(const char* d, int size) : len(strlen(d)), size(size), front(0), rear(len) {
data = new char[size];
strcpy(data, d);
}
Queue::~Queue(){delete [] data;}
Queue::Queue(const Queue &other) : len(other.len), size(other.size), front(other.front), rear(other.rear) {
data = new char[size];
strcpy(data, other.data);
}
Queue& Queue::operator= (const Queue &other) {
if (this != &other) {
delete[] data;
len = other.len;
size = other.size;
front = other.front;
rear = other.rear;
data = new char[size];
strcpy(data, other.data);
}
return *this;
}
char Queue::MyFront(){
if (empty()) {
cout<<"队列为空"<<endl;
exit(EXIT_SUCCESS);
}
return data[front];
}
char Queue::back(){
if (empty()) {
cout<<"队列为空"<<endl;
exit(EXIT_SUCCESS);
}
return data[rear - 1];
}
bool Queue::empty(){
return front == rear && len == 0;
}
int Queue::MySize(){
return len;
}
void Queue::push(char e) {
if (len >= size) {
cout << "队列已满" << endl;
return;
}
data[rear++] = e;
len++;
data[rear] = '\0';
}
void Queue::emplace(char e) {
push(e);
}
char Queue::pop() {
if (empty()) {
cout << "队列为空" << endl;
exit(EXIT_FAILURE);
}
len--;
return data[front++];
}
void Queue::swap(Queue &other) {
std::swap(len, other.len);
std::swap(size, other.size);
std::swap(front, other.front);
std::swap(rear, other.rear);
std::swap(data, other.data);
}
main.cpp
#include "MyQueue.h"
int main() {
Queue q("hello world",20);
q.emplace('A');
q.emplace('B');
q.emplace('C');
cout << "q队首数据:" << q.MyFront() << endl;
cout << "q队尾数据:" << q.back() << endl;
cout << "q队列数据数量 " << q.MySize() << endl;
cout<<"q尾删操作"<<endl;
q.pop();
cout << "q队首数据:" << q.MyFront()<< endl;
Queue q1;
q1 = q;
cout << "s队首数据:" << q1.MyFront() << endl;
cout << "s队尾数据:" << q1.back() << endl;
Queue q2("nihao", 20);
cout<<"交换操作"<<endl;
q.swap(q2);
cout << "q队首数据:" << q.MyFront() << endl;
cout << "q队尾数据:" << q.back() << endl;
cout << "q2队首数据:" << q2.MyFront() << endl;
cout << "q2队尾数据:" << q2.back() << endl;
return 0;
}
运行结果
思维导图