思维导图
作业
自己封装 栈和队列
栈
#include <iostream>
using namespace std;
class mystack
{
private:
int *data;
int top;
public:
mystack():data(NULL),top(-1){}
~mystack(){delete[] data;}
mystack & operator=(const mystack &R)
{
if(this!=&R)
{
delete []this->data;
this->data=new int[R.top+1];
for(int i=0;i<=R.top;i++)
{
*(this->data+i)=*(R.data+i);
}
this->top=R.top;
}
return *this;
}
bool empty()
{
return top==-1;
}
int size()
{
return top+1;
}
bool push(int e)
{
int *temp=new int[top+2];
for(int i=0;i<=top;i++)
{
*(temp+i)=*(data+i);
}
top++;
*(temp+top)=e;
if(top>0)
{
delete []data;
}
data=temp;
return true;
}
bool pop()
{
*(data+top)='\0';
top--;
return true;
}
void show()
{
for(int i=top;i>-1;i--)
{
cout<<"第"<<i<<"个元素为:"<<data[i]<<endl;
}
}
};
int main()
{
mystack a;
a.push(3);
a.show();
a.push(4);
a.show();
a.push(2);
a.show();
a.push(1);
a.show();
mystack b;
b.push(4);
b.push(7);
b.show();
cout<<b.size()<<endl;
b=a;
b.show();
cout<<b.size()<<endl;
return 0;
}
队列
#include <iostream>
using namespace std;
class myqueue
{
private:
int* data;
int front;
int tail;
public:
myqueue():data(NULL),front(0),tail(0){}
~myqueue(){delete[]data;}
myqueue & operator=(const myqueue &R)
{
delete []this->data;
this->data=new int[R.tail+1];
for(int i=0;i<=R.tail;i++)
{
*(this->data+i)=*(R.data+i);
}
this->tail=R.tail;
this->front=R.front;
return *this;
}
int &Front()
{
return *(data+front);
}
int &Tail()
{
return *(data+tail-1);
}
bool empty()
{
return front==tail;
}
int size()
{
return tail-front;
}
bool push(int e)
{
int *temp=new int[tail+2];
for(int i=0;i<tail;i++)
{
*(temp+i)=*(data+i);
}
*(temp+tail)=e;
tail++;
if(tail>1)
{
delete[]data;
}
data=temp;
return true;
}
bool pop()
{
*(data+front)='\0';
front++;
return true;
}
void show()
{
for(int i=front;i<tail;i++)
{
cout<<"第"<<i<<"个元素为:"<<data[i]<<endl;
}
}
};
int main()
{
myqueue a;
a.push(2);
a.show();
a.push(4);
a.push(7);
a.show();
a.pop();
a.show();
a.pop();
a.show();
a.push(9);
a.show();
cout<<a.size()<<endl;
a.Front()=1;
a.show();
a.Tail()=10;
a.show();
return 0;
}