class类实现栈、队列

在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;
}

这个是将队列与树结合,用来判断完全二叉树问题 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值