自己封装 栈和队列
#include <iostream>
using namespace std;
class mystack
{
private:
int *data;
int size;
int top;
public:
//无参构造
mystack():size(10)
{
data = new int[size];
top = -1;
size =10;
}
//有参构造
mystack(int s)
{
data = new int[s];
top = -1;
size = s;
}
//赋值
mystack &operator=(mystack &R)
{
delete []this;
data = new int[R.size];
size = R.size;
top = R.top;
return *this;
}
//访问栈顶元素
int gettop()
{
return data[top];
}
//判空
bool empty()
{
return top==-1;
}
//求最大容量
int getsize()
{
return size;
}
//向栈顶插入元素
void push(int a)
{
if(top==size-1)
{
expend(); //二倍扩容
}
data[top+1] = a;
top++;
}
//删除栈顶元素
void pop()
{
data[top] = 0;
top--;
}
//输出栈中元素
void show()
{
for(int i=0;i<=top;i++)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
//二倍扩容
void expend()
{
int *temp = new int[size*2];
for(int i=0;i<size;i++)
{
temp[i] = data[i];
}
delete []data;
data = temp;
size = size*2;
}
};
int main()
{
mystack s(3);
s.push(99);
s.push(77);
s.push(88);
//s.pop();
s.show();
cout<<"size="<<s.getsize()<<endl;
s.push(66);
s.show();
cout<<"size="<<s.getsize()<<endl;
return 0;
}
#include <iostream>
using namespace std;
class myqueue
{
private:
int *data;
int size;
int front;
int tail;
public:
//无参构造
myqueue():size(10)
{
data = new int[size];
size =10;
front = 0;
tail = 0;
}
//有参构造
myqueue(int s)
{
data = new int[s];
size = s;
front = 0;
tail = 0;
}
//赋值
myqueue &operator=(myqueue &R)
{
delete []this;
data = new int[R.size];
size = R.size;
front = R.front;
tail = R.tail;
return *this;
}
//访问第一个元素
int getfront()
{
if(empty())
{
cout<<"队列中没有元素"<<endl;
return -1;
}
return data[front];
}
//访问最后一个元素
int back()
{
if(empty())
{
cout<<"队列中没有元素"<<endl;
return -1;
}
return data[tail];
}
//判空
bool empty()
{
return front==tail;
}
//判满
bool full()
{
return (tail+1)%size == front;
}
//求最大容量
int getsize()
{
return size;
}
//向队列尾部插入元素
void push(int a)
{
if(full())
{
cout<<"队列满了"<<endl;
}
else
{
data[tail] = a;
tail = (tail+1)%size;
}
}
//删除首个元素
void pop()
{
if(empty())
{
cout<<"队列为空"<<endl;
return ;
}
data[front] = 0;
front = (front+1)%size;
}
//输出栈中元素
void show()
{
if(empty())
{
cout<<"队列为空"<<endl;
return ;
}
for(int i=front;i!=tail;i=(i+1)%size)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
};
int main()
{
myqueue q1(4);
q1.push(66);
q1.push(77);
q1.push(88);
q1.show();
q1.pop();
q1.push(99);
q1.show();
return 0;
}
思维导图