自己实现queue(队列) 和 stack(栈)
stack:
#include <iostream>
#include<vector>
using namespace std;
template<typename T>
class mystack
{
private:
vector<T> v;
public:
mystack(){}
mystack(const mystack& c)
{
this->v=c.v;
}
~mystack(){}
bool empty()
{
return this->v.empty();
}
bool full()
{
return this->v.full();
}
void push(int e)
{
this->v.push_back(e);
}
T top()
{
if(this->empty())
{
cout<<"empty"<<endl;
return -1;
}
return this->v.back();
}
void pop()
{
if(this->empty())
{
cout<<"empty"<<endl;
}
this->v.pop_back();
}
size_t size()
{
return this->v.size();
}
};
int main()
{
mystack<int> m;
cout<<m.empty()<<endl;
m.pop();
for(int i=1;i<=10;i++)
{
m.push(i);
cout<<m.top()<<" ";
}
return 0;
}
queue:
#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()
{
myqueue<int> m1;
cout<<m1.empty()<<endl;
for(int i=1;i<=20;i++)
{
m1.push(i);
cout<<m1.size()<<endl;
}
}