作业内容
用C++封装栈容器库
用C++封装队列容器库
栈代码
在这里插入代码片#include <iostream>
#define LEN 100
using namespace std;
template <typename T>
class mystack
{
private:
T date[LEN];
int top;
public:
//构造函数
mystack()
{
top = -1;
}
//析构函数
~mystack(){}
//拷贝赋值函数
mystack& operator=(const mystack& other)
{
memcpy(this->data,other.date,LEN);
this->top = other.top;
}
//栈顶元素访问
T top_()
{
if(empty() == true)
{
cout<<"空栈"<<endl;
throw -1;
}
cout<<this->date[top]<<endl;
return this->date[top];
}
//判空
bool empty()
{
return (top == -1);//判断栈顶是否有值,没有则栈空,返回failse
}
//判满
bool full()
{
return (top == LEN-1);
}
//容纳的元素数
int size()
{
return top+1;
}
//向栈顶插入元素
void push(T e)
{
if(full() == true)
{
cout<<"栈已满"<<endl;
return;
}
top++;
this->date[top]=e;
}
//删除栈顶元素
void pop()
{
if(empty() == true)
{
cout<<"空栈"<<endl;
return;
}
top--;
}
};
int main()
{
mystack<int> v;
v.push(1);
v.top_();
return 0;
}
队列代码
在这里插入代码片#include <iostream>
#define LEN 100
using namespace std;
template <typename T>
class myqueue
{
private:
T date[LEN];
int front;
int back;
public:
//构造函数
myqueue()
{
this->date = front;
back=front;
}
//析构函数
~myqueue(){}
//拷贝赋值函数
myqueue& operator=(const myqueue& other)
{
memcpy(this->data,other.date,LEN);
this->front = other.front;
this->back = other.back;
}
//访问第一个元素
T v_front()
{
if(empty() == true)
{
cout<<"空队列"<<endl;
throw -1;
}
return this->date[front];
}
//访问最后一个元素
T v_back()
{
if(empty() == true)
{
cout<<"空队列"<<endl;
throw -1;
}
return this->date[back-1];
}
//判空
bool empty()
{
return (back == front);//队尾是否等于队头
}
//判满
bool full()
{
return (back == LEN);
}
//容纳的元素数
int size()
{
return back+1;
}
//向队尾插入元素
void push(T e)
{
if(full() == true)
{
cout<<"队列已满"<<endl;
return;
}
back++;
this->date[back]=e;
}
//删除队头元素
void pop()
{
if(empty() == true)
{
cout<<"空队列"<<endl;
return;
}
front--;
}
};
int main()
{
}