1 思维导图
2 顺序栈模板和顺序队列模板
#include <iostream>
using namespace std;
template <typename T>
class My_stack
{
private:
T *ptr; //指向堆区空间
int top; //记录栈顶元素
public:
//无参构造
My_stack():ptr(new T[10]), top(-1){}
//有参构造
My_stack(int size = 10):ptr(new T[size]), top(-1){}
//析构函数
~My_stack(){}
//判空函数
bool My_empty()
{
if (-1 == top)
return true;
return false;
}
//判满函数
bool My_full(int size = 10)
{
if (top == size - 1)
return true;
return false;
}
//入栈函数
void My_inqueue(T n)
{
*(ptr+(++top)) = n;
}
//出栈函数
void My_push()
{
cout << "出栈元素:" << *(ptr+(top--)) <<endl;
}
//遍历函数
void output()
{
cout << "遍历:";
for (int i=0; i<=top; i++)
{
cout << ptr[i] << " ";
}
cout <<endl;
}
//获取栈顶元素的引用
int Top()
{
cout << "栈顶元素:" << *(ptr+top) <<endl;
return *(ptr+top);
}
//返回容纳的元素个数
void My_size()
{
cout << "元素个数:" << top+1 <<endl;
}
};
int main()
{
int size, n;
char m;
cout << "请输入队列容量:";
cin >> size;
My_stack <int> s(size);
while(1)
{
if (s.My_full(size))
{
cout << "队列满" <<endl;
break;
}
cout << "输入入栈元素:";
cin >> n;
s.My_inqueue(n);
}
while(1)
{
cout << "是否出栈y/n:";
cin >> m;
if ('n' == m)
break;
if (s.My_empty())
{
cout << "队列空" <<endl;
break;
}
s.My_push();
s.output();
}
s.Top();
s.My_size();
return 0;
}
#include <iostream>
using namespace std;
template <typename T>
class My_stack
{
private:
T *ptr; //指向堆区空间
int front; //队头
int rear; //队尾
public:
//无参构造
My_stack():ptr(new T[10]), front(0), rear(0){}
//有参构造
My_stack(int size = 10):ptr(new T[size]), front(0), rear(0){}
//析构函数
~My_stack()
{
delete []ptr;
}
//判空函数
bool My_empty()
{
if (rear == front)
return true;
return false;
}
//判满函数
bool My_full(int size)
{
if (front == (rear+1)%size)
return true;
return false;
}
//入队函数
void My_ins(T n, int size)
{
ptr[rear] = n;
rear = (rear+1)%size;
}
//出队函数
void My_push(int size)
{
cout << "出队元素:" << ptr[front] <<endl;
front = (front+1)%size;
}
//遍历函数
void output(int size)
{
cout << "遍历:";
for (int i=front; i!=rear; i=(i+1)%size)
{
cout << ptr[i] << " ";
}
cout <<endl;
}
//元素个数
void My_number(int size)
{
cout << "元素个数:" << (size-front+rear)%size <<endl;
}
//访问第一个元素
void My_front()
{
cout << "front = " << ptr[front] <<endl;
}
//访问最后的元素
void My_back()
{
cout << "rear = " << ptr[rear-1] <<endl;
}
};
int main()
{
int size, n;
char m;
cout << "请输入队列容量:";
cin >> size;
My_stack <int> s(size);
while(1)
{
if (s.My_full(size))
{
cout << "队列满" <<endl;
break;
}
cout << "输入入队元素:";
cin >> n;
s.My_ins(n, size);
}
while(1)
{
cout << "是否出队y/n:";
cin >> m;
if ('n' == m)
break;
if (s.My_empty())
{
cout << "队列空" <<endl;
break;
}
s.My_push(size);
s.output(size);
s.My_number(size);
s.My_front();
s.My_back();
}
return 0;
}