【面试准备】数据结构-队列

#include <iostream>
using namespace std;

template <class T>
struct SLNode{
	T data;
	SLNode<T>* next;

	SLNode(SLNode* nextnode = NULL){
		next = nextnode;
	}

	SLNode(const T& item,SLNode* nextnode = NULL){
		data = item;
		next = nextnode;
	}
};

template<class T>
class LQueue{
private:
	SLNode<T> *front,*rear;
public:
	LQueue(){
		front = NULL;
		rear = NULL;
	}
	~LQueue(){
		Clear();
	}
	int IsEmpty(){
		return front==NULL;
	}
	void Insert(T& item);
	bool Delete(T& item);
	bool Front(T& item);
	void Clear();
	void Show();
};

template<class T>
void LQueue<T> :: Insert(T& item){
	SLNode<T>* s = new SLNode<T>(item);
	if(IsEmpty()){
		front = s;
	}
	else{
		rear->next = s;
	}
	rear = s;
}

template<class T>
bool LQueue<T> :: Delete(T& item){
	if(IsEmpty()){
		cout<<"错误!队列为空!"<<endl;
		return false;
	}
	SLNode<T> *p = front;
	item = front->data;
	front = front->next;
	delete p;
	if(IsEmpty()){
		rear = NULL;
	}
	return true;
}

template<class T>
bool LQueue<T> :: Front(T& item){
	if(IsEmpty()){
		cout<<"错误!队列为空!"<<endl;
		return false;
	}
	item = front->data;
	return true;
}

template<class T>
void LQueue<T> :: Clear(){
	if(IsEmpty()){
		return ;
	}
	SLNode<T>* p = front;
	while(front!=rear){
		delete p;
		front = front->next;
		p = front;
	}
	delete front;
}

template<class T>
void LQueue<T> :: Show(){
	if(IsEmpty()){
		cout<<"队列为空!"<<endl;
		return ;
	}
	SLNode<T>* p = front;
	while(p!=NULL){
		if(p->next==NULL){
			cout<<p->data<<endl;
			return ;
		}
		cout<<p->data<<"->";
		p = p->next;
	}
	return ;
}

int main(){
	int i = 0;
	LQueue<int>* p = new LQueue<int>;
	for(i = 0; i < 10 ; ++i){
		p->Insert(i);
	}
	p->Show();
	int xx,aa;
	for(i = 0 ; i< 10 ; ++i){
		p->Front(xx);
		p->Delete(aa);
		cout<<i<<"::"<<xx<<"=="<<aa<<endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值