#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;
}
【面试准备】数据结构-队列
最新推荐文章于 2014-11-25 00:15:27 发布