1、实现类似stack的基础模板类
#include <iostream>
#include <cstring>
using namespace std;
template<class T>
class mystack {
private:
int top;
T *arr;
T *end;
public:
mystack(int size=16)
{
this->arr=new T[size];
this->end=this->arr+size;
this->top=-1;
}
~mystack()
{
delete []arr;
end=arr=nullptr;
}
mystack(const mystack &other)
{
int size=other.end-other.arr;
this->arr=new T[size];
memcpy(arr,other.arr,(other.top+1)*sizeof(T));
this->top=other.top;
this->end=other.end;
}
mystack &operator=(const mystack &other)
{
if(this!=&other){
int size=other.end-other.arr;
T *temp=new T[size];
memcpy(temp,other.arr,(other.top+1)*sizeof(T));
delete []arr;
this->arr=temp;
this->top=other.top;
this->end=other.end;
}
return *this;
}
void enlarge()
{
int size=end-arr;
T *temp=new T[2*size];
memcpy(temp,arr,size*sizeof(T));
delete []arr;
arr=temp;
end=arr+2*size;
}
T &gettop()
{
return arr[top];
}
int size()
{
return top+1;
}
bool empty()
{
return top==-1;
}
void push(T val)
{
top++;
int size=end-arr;
if(top>=size){
enlarge();
}
arr[top]=val;
}
T &pop()
{
top--;
return arr[top+1];
}
};
int main(int argc,const char *argv[])
{
mystack<int> s;
cout<<"size="<<s.size()<<endl;
for(int i=1;i<=20;i++){
s.push(i);
}
cout<<"size="<<s.size()<<endl;
while(!s.empty()){
cout<<s.pop()<<" ";
}
cout<<endl;
cout<<"size="<<s.size()<<endl;
return 0;
}
运行效果:
2、实现类似queue的基础模板类
#include <iostream>
using namespace std;
template<class T>
class myqueue {
private:
typedef struct node {
T data;
struct node *next;
}Queue;
Queue *head;
Queue *tail;
int size;
public:
myqueue()
{
head=tail=nullptr;
size=0;
}
~myqueue()
{
while(!empty()){
pop();
}
}
myqueue(const myqueue &other)
{
head=tail=nullptr;
size=0;
Queue *temp=other.head;
while(temp!=other.tail->next){
push(temp->data);
temp=temp->next;
}
}
myqueue &operator=(const myqueue &other)
{
if(this!=&other){
while(!empty()){
pop();
}
Queue *temp=other.head;
while(temp!=other.tail->next){
push(temp->data);
temp=temp->next;
}
}
return *this;
}
int getsize()
{
return size;
}
bool empty()
{
return head==nullptr && tail==nullptr;
}
T &front()
{
return head->data;
}
T &back()
{
return tail->data;
}
void push(T val)
{
Queue *temp=new Queue;
temp->data=val;
temp->next=nullptr;
if(empty()){
head=tail=temp;
}else{
tail->next=temp;
tail=temp;
}
size++;
}
T pop()
{
Queue *temp=head;
T tempdata=temp->data;
head=head->next;
delete temp;
size--;
if(head==nullptr){
tail=nullptr;
}
return tempdata;
}
};
int main(int argc,const char *argv[])
{
myqueue<int> q;
cout<<"size="<<q.getsize()<<endl;
for(int i=1;i<=20;i++){
q.push(i);
}
cout<<"size="<<q.getsize()<<endl;
cout<<"第一个元素为:"<<q.front()<<endl;
cout<<"最后一个元素为:"<<q.back()<<endl;
while(!q.empty()){
cout<<q.pop()<<" ";
}
cout<<endl;
cout<<"size="<<q.getsize()<<endl;
return 0;
}
运行效果: