1、通过模板类写一个栈,实现Push和Pop操作。
应用:将任一十进制数转换成十六进制数。
#include <iostream>
using namespace std;
const int maxn=1e4+10;
template <class T>
class Stack
{
T stk[maxn];
int top;
public:
Stack()
{
top=0; //初始化栈顶指针
}
void Push(T x);
T Pop();
bool Stackfull();
bool Stackempty();
};
template <class T>
bool Stack<T>::Stackfull() //判断栈是否已满
{
return top==maxn-1; //若top==maxn-1 ,返回true,否则返回false
}
template <class T>
bool Stack<T>::Stackempty() //判断栈是否为空
{
return top==0; //若top==0,返回true,否则返回false
}
template <class T>
void Stack<T>::Push(T x){
if(Stackfull())
{
cout<<"Stack is full!"<<endl;
return ;
}
stk[top++]=x;
}
template <class T>
T Stack<T>::Pop()
{
if(Stackempty()){
cout<<"Stack is empty!"<<endl;
return 0;
}
return stk[--top];
}
int main()
{
Stack<int> st;
int n;
cin>>n;
while(n)
{
st.Push(n%16);
n/=16;
}
while(!st.Stackempty())
{
int x=st.Pop();
if(x<9) cout<<x;
else cout<<char(x-10+'A');
}
cout<<endl;
return 0;
}
2、手写队列类模板 实现Push与Pop操作:
通过head指针与tail指针的指向来判断队列是否为空或已满。
①当head==tail时,说明队列为空。
②当(tail+1)%(队列长度)==head时,说明队列已满。//因为运用循环队列思想,所以通过取模运算实现循环
应用:
模拟银行排队取号、叫号系统:
#include <iostream>
using namespace std;
const int maxn=1e2+10;
template <class T>
class Queue
{
T que[maxn];
int head,tail;
public:
Queue()
{
head=tail=-1; //head 、tail指向队首元素的前一个位置
}
bool QueEmpty()
{
return head==tail;
}
bool QueFull()
{
return (tail+1)%maxn==head;
}
void Push(T x)
{
if(QueFull()){
cout<<"等待队列已满"<<endl;
return ;
}
tail++;
tail%=maxn; //tail指针后移 实现入队操作
que[tail]=x;
}
T Pop()
{
if(QueEmpty())
{
cout<<"当前队列为空"<<endl;
return 0;
}
head++;
head%=maxn;
return que[head]; //head 指针后移,实现出队操作
}
};
int main()
{
Queue<int> q;
int num=0,choice=0; //num代表排队序号,choice 表示客户的选择
do{
cout<<"******** -1- 要号********"<<endl;
cout<<"******** -2- 叫号********"<<endl;
cout<<"******** -0- 退出********"<<endl;
cout<<"Choose the serve"<<endl;
cin>>choice;
switch(choice) //简单的switch选择结构
{
case 1:
{
q.Push(++num);
cout<<"您的等待序号为"<<num<<endl;
break;
}
case 2:
{
cout<<"请"<<q.Pop()<<"号客户到柜台办理业务"<<endl;
break;
}
case 0:
{
cout<<"-quit-"<<endl;
break;
}
default:
{
cout<<"-error-"<<endl;
break;
}
}
}while(choice);
return 0;
}
蒟蒻求神犇轻喷……