1.C++实现栈容器
代码
#include <iostream>
using namespace std;
template<typename T>
class stack
{
private:
T* top;
T* bottom;
T* end;
public:
stack(int size=2)
{
bottom=new T[size];
top=bottom;
end=bottom+size;
}
~stack()
{
delete []bottom;
top=bottom=end=NULL;
}
stack(const stack& other)
{
int len=other.top-other.bottom;
int size=other.end-other.bottom;
this->bottom=new T[size];
memcpy(this->bottom,other.bottom,sizeof(T)*len);
this->top=this->bottom+len;
this->end=this->bottom+size;
}
bool full()
{
return this->end==this->top;
}
bool empty() const
{
return this->top==this->bottom;
}
int len()
{
return this->top-this->bottom;
}
int size()
{
return this->end-this->bottom;
}
void greater()
{
int size=this->end-this->bottom;
T* temp=new T[2*size];
memcpy(temp,this->bottom,sizeof(T)*size);
delete []bottom;
bottom=temp;
top=bottom+size;
end=bottom+2*size;
}
void push(const T val)
{
if(this->full())
{
this->greater();
}
*top=val;
top++;
}
void pop()
{
if(this->empty())
{
return;
}
top--;
}
T &at(int index)
{
if(index<0 || index>this->len())
{
cout<<"访问越界"<<endl;
}
return bottom[index];
}
};
int main()
{
stack<int> s1;
cout<<"入栈十个数"<<endl;
for(int i=1;i<=10;i++)
{
s1.push(i);
}
cout<<"遍历"<<endl;
for(int i=0;i<10;i++)
{
cout<<s1.at(i)<<" ";
}
cout<<endl<<"出栈五个数"<<endl;
for(int i=1;i<=5;i++)
{
s1.pop();
}
cout<<"遍历"<<endl;
for(int i=0;i<5;i++)
{
cout<<s1.at(i)<<" ";
}
cout<<endl;
return 0;
}
结果
2.C++实现队列容器
代码
#include <iostream>
using namespace std;
template<typename T>
class queue
{
private:
T* front;
T* back;
T* end;
public:
queue(int size=2)
{
back=new T[size];
front=back;
end=back+size;
}
~queue()
{
delete []back;
front=end=back=NULL;
}
queue(const queue& other)
{
int len=other.front-other.back;
int size=other.end-other.back;
this->back=new T[size];
memcpy(this->back,other.back,sizeof(T)*len);
this->front=this->back+len;
this->end=this->back+size;
}
bool full()
{
return this->end==this->front;
}
bool empty()
{
return this->front==this->back;
}
void greater()
{
int size=this->end-this->back;
T*temp=new T[2*size];
memcpy(temp,this->back,sizeof(T)*size);
delete []back;
back=temp;
front=back+size;
end=back+2*size;
}
void push(const T val)
{
if(this->full())
{
this->greater;
}
*front=val;
front++;
}
void pop()
{
if(this->empty())
{
return ;
}
//cout<<*back<<endl;
back++;
}
int len()
{
return front-back;
}
int size()
{
return end-back;
}
T &at(int index)
{
if(index<0 || index>this->len())
{
cout<<"访问越界"<<endl;
}
return back[index];
}
};
int main()
{
queue<int> q1;
cout<<"入队列十个数"<<endl;
for(int i=1;i<=10;i++)
{
q1.push(i);
}
cout<<"遍历"<<endl;
for(int i=0;i<10;i++)
{
cout<<q1.at(i)<<" ";
}
cout<<endl<<"出队列五个数"<<endl;
for(int i=1;i<=5;i++)
{
q1.pop();
}
cout<<"遍历"<<endl;
for(int i=0;i<5;i++)
{
cout<<q1.at(i)<<" ";
}
return 0;
}
结果