1、仿照stack类实现my_stack,实现一个栈的操作
#include <iostream>
using namespace std;
class My_stack
{
private:
char *ptr;
int size;
int top;
public:
My_stack():size(20),top(-1)
{
ptr = new char[size];
}
My_stack(int num)
{
size = num;
ptr = new char[num];
top = -1;
}
My_stack(const My_stack &other)
{
top = other.top;
size = other.size;
ptr = new char[size];
for(int i=0;i<size;i++)
{
ptr[i] = other.ptr[i];
}
}
My_stack &operator=(const My_stack &other)
{
if(this==&other)
{
return *this;
}
delete [] ptr;
top = other.top;
size = other.size;
ptr = new char[size];
for(int i=0;i<size;i++)
{
ptr[i] = other.ptr[i];
}
return *this;
}
char My_top()
{
return ptr[top];
}
void My_empty()
{
if(top==-1)
{
cout<<"栈为空"<<endl;
}
else
{
cout<<"栈不为空"<<endl;
}
}
int My_size()
{
return top+1;
}
void My_push(const char dat)
{
if(top+1==size)
{
cout<<"栈满不能继续添加"<<endl;
}
else
{
ptr[++top] = dat;
}
}
void My_pop()
{
ptr[top--] = 0;
}
};
int main()
{
My_stack my_stack;
my_stack.My_push('1');
my_stack.My_push('2');
my_stack.My_push('3');
cout << "Top: " << my_stack.My_top() <<endl;
my_stack.My_pop();
my_stack.My_empty();
cout << "Size: " << my_stack.My_size() <<endl;
return 0;
}
2、实现一个队列
#include <iostream>
using namespace std;
#include <iostream>
#include <stdexcept>
class My_queue
{
private:
char *ptr;
int size;
int back;
int fro;
public:
My_queue():size(20),back(0),fro(0)
{
ptr = new char[size];
}
My_queue(int num)
{
size = num;
ptr = new char[num];
back = 0;
fro = 0;
}
~My_queue()
{
delete [] ptr;
}
My_queue(const My_queue &other)
{
fro = other.fro;
back = other.back;
size = other.size;
ptr = new char[size];
for(int i=0;i<size;i++)
{
ptr[i] = other.ptr[i];
}
}
My_queue &operator=(const My_queue &other)
{
if(this==&other)
{
return *this;
}
delete [] ptr;
fro = other.fro;
back = other.back;
size = other.size;
ptr = new char[size];
for(int i=0;i<size;i++)
{
ptr[i] = other.ptr[i];
}
return *this;
}
char My_front()
{
return ptr[fro];
}
char My_back()
{
return ptr[back-1];
}
bool My_empty()
{
return fro == back;
}
int My_size()
{
return back - fro;
}
void My_push(const char dat)
{
if(back+1==size)
{
cout<<"栈满不能继续添加"<<endl;
}
else
{
ptr[back++] = dat;
}
}
void My_pop()
{
ptr[fro++] = 0;
}
};
int main()
{
My_queue my_queue;
my_queue.My_push('1');
my_queue.My_push('2');
cout << "Front: " << my_queue.My_front() <<endl; // 输出 1
cout<<"back:"<<my_queue.My_back()<<endl;
cout << "Size: " << my_queue.My_size() << endl; // 输出 1
return 0;
}
3、思维导图