在c++中,STL里有stack和queue两个封装函数,一直不知道是怎么实现的,直到在网上看到了class类,然后自己写了一下特此记录
栈
class stack{
public:
stack();
void pop();
void push(char c);
char top();
void show();
bool empty(){
return _top==-1;
};
bool full(){
return _top==665;
}
private:
char ch[666];
int _top;
};
stack::stack(){
_top=-1;
}
void stack::push(char c){
if(full()) return ;
ch[++_top]=c;
}
void stack::pop(){
if(empty()) return ;
_top--;
}
void stack::show(){
if(empty()) return ;
int i;
for(i=0;i<=_top;i++) printf("%c",ch[i]);
putchar('\n');
}
char stack::top(){
if(empty()) return 0;
return ch[_top];
}
队列
#include<stdio.h>
#include<stdlib.h>
/*
输入一串数字按有序二叉树建树,到0结束
并判断该二叉树是否为完全二叉树
*/
typedef struct bitnode{
int date;
struct bitnode *lchild,*rchild;
struct bitnode *next;
}bitnode;
class queue{
public:
queue();
bitnode *top();
void pop();
void push(bitnode *t);
bool empty(){
return sum==0;
}
private:
bitnode *first;
bitnode *last;
int sum;
};
bitnode *insert(bitnode *t,int num){
bitnode *p=t;
bitnode *pnew=(bitnode *)malloc(sizeof(*pnew));
pnew->date=num;
pnew->lchild=NULL;
pnew->rchild=NULL;
if(t==NULL) t=pnew;
else{
while(1){
if(num>p->date){
if(!p->rchild){
p->rchild=pnew;
break;
}
else p=p->rchild;
}
else if(num<p->date){
if(!p->lchild){
p->lchild=pnew;
break;
}
else p=p->lchild;
}
else break;
}
}
return t;
}
bitnode *create_tree(){
bitnode *t=NULL;
int num;
while(1){
scanf("%d",&num);
if(!num) break;
t=insert(t,num);
}
return t;
}
queue::queue(){
first=NULL;
last=NULL;
sum=0;
}
bitnode *queue::top(){
return first;
}
void queue::pop(){
if(first){
bitnode *p=first;
first=first->next;
p->next=NULL;
free(p);
sum--;
if(!sum) last=NULL;
}
}
void queue::push(bitnode *t){
bitnode *pnew=t;
if(!first){
first=pnew;
last=pnew;
}
else{
last->next=pnew;
last=pnew;
}
sum++;
}
int main(){
queue q;
int flag=0;
bitnode *t=create_tree();
q.push(t);
while(!q.empty()){
bitnode *p=q.top();
if(p->lchild){
if(flag){
printf("No!\n");
break;
}
q.push(p->lchild);
}
else flag=1;
if(p->rchild){
if(flag){
printf("No!\n");
break;
}
q.push(p->rchild);
}
else flag=1;
q.pop();
}
if(q.empty()) printf("Yes!\n");
return 0;
}
这个是将队列与树结合,用来判断完全二叉树问题