作业内容
在C++环境下手动封装栈和队列容器库
代码部分
#include <iostream>
#define MAX_SIZE 128
using namespace std;
template<typename T>
class MyStack
{
private:
T data[MAX_SIZE];
int top;
public:
//构造函数
MyStack()
{
top = -1;
}
//析构函数
~MyStack(){}
//拷贝构造函数
MyStack(const MyStack& other)
{
memcpy(this->data,other.data,MAX_SIZE);
this->top = other.top;
}
//拷贝赋值函数
MyStack& operator=(const MyStack& other)
{
memcpy(this->data,other.data,MAX_SIZE);
this->top = other.top;
return *this;
}
//判空
bool isEmpty()
{
return top==-1;
}
//访问栈顶元素
T getTop()
{
if(isEmpty())
throw -1;
return data[top];
}
//判满
bool isFull()
{
return top==MAX_SIZE-1;
}
//返回容纳的元素数
int size()
{
return top+1;
}
//入栈
void push(T t)
{
if(isFull())
throw -1;
top++;
data[top] = t;
}
//出栈
void pop()
{
if(isEmpty())
throw -1;
top--;
}
//交换内容
void swap(MyStack& other)
{
T temp_arr[MAX_SIZE];
int temp_top;
memcpy(temp_arr, this->data, MAX_SIZE);
memcpy(this->data, other.data, MAX_SIZE);
memcpy(other.data, temp_arr, MAX_SIZE);
temp_top = this->top;
this->top = other.top;
other.top = temp_top;
}
};
template<typename T>
class MyQueue
{
private:
T data[MAX_SIZE];
int front;
int back;
public:
//构造函数
MyQueue()
{
front = 0;
back = 0;
}
//析构函数
~MyQueue(){}
//拷贝构造函数
MyQueue(const MyQueue& other)
{
memcpy(this->data,other.data,MAX_SIZE);
this->front = other.front;
this->back = other.back;
}
//拷贝赋值函数
MyQueue& operator=(const MyQueue& other)
{
memcpy(this->data,other.data,MAX_SIZE);
this->front = other.front;
this->back = other.back;
return *this;
}
//判空
bool empty()
{
return front == back;
}
//判满
bool full()
{
return back == MAX_SIZE;
}
//访问第一个元素
T getfront()
{
if(empty())
throw -1;
return data[front];
}
//访问最后一个元素
T getback()
{
if(empty())
throw -1;
return data[back-1];
}
//返回容纳的元素数
int size()
{
return back-front;
}
//入队
void push(T t)
{
if(full())
throw -1;
data[back] = t;
back++;
}
//出队
void pop()
{
if(empty())
throw -1;
front++;
}
//交换内容
void swap(MyQueue& other)
{
T temp_arr[MAX_SIZE];
int temp;
memcpy(temp_arr, this->data, MAX_SIZE);
memcpy(this->data, other.data, MAX_SIZE);
memcpy(other.data, temp_arr, MAX_SIZE);
temp = this->front;
this->front = other.front;
other.front = temp;
temp = this->back;
this->back = other.back;
other.back = temp;
}
};
int main()
{
MyStack<int> ms;
MyStack<int> ms1;
cout<<ms.isEmpty()<<endl;
ms.push(520);
ms.push(1314);
cout<<ms.getTop()<<endl;
cout<<ms.size()<<endl;
ms.pop();
cout<<ms.getTop()<<endl;
ms1.push(666);
ms.swap(ms1);
cout<<ms.getTop()<<endl;
MyQueue<int> mq;
MyQueue<int> mq1;
cout<<mq.empty()<<endl;
mq.push(999);
mq.push(777);
cout<<mq.getfront()<<endl;
cout<<mq.getback()<<endl;
cout<<mq.size()<<endl;
mq.pop();
cout<<mq.getfront()<<endl;
mq1.push(123);
mq.swap(mq1);
cout<<mq.getfront()<<endl;
return 0;
}