//practice for queue with integer data type
//Apr 4
#ifndef _MO_INT_QUEUE
#define _MO_INT_QUEUE
#include
using namespace std;
class Queue;
class Node{
int _data;
Node* next;
public:
friend class Queue;
Node(int data, Node* next);
};
class Queue{
Node* head;
Node* tail;
public:
Queue();
void Add(int data);
int& remove();
bool IsEmpty();
~Queue();
};
#endif
//int_queue.cpp
// Apr 4
#include "int_queue.h"
#include
using namespace std;
Node::Node(int data, Node *next){
this->_data=data;
this->next=next;
}
Queue::Queue(){
head=tail=(Node*)0;//queue is empty at beginning
}
void Queue::Add(int data){
if(!head){// add the first node
head=new Node(data,tail);
}
else{
if(!tail){//add the 2nd node
tail=new Node(data,(Node*)0);
head->next=tail;
}else{//in case there are more than two nodes
Node* temp=new Node(data,(Node*)0);
tail->next=temp;
tail=temp;
}
}
}
int& Queue::remove(){
int ret=head->_data;
Node* ToDel;
if(head==tail)//in case there is only one node left
head=tail=(Node*)0;
else{
ToDel=head;
head=head->next;
delete ToDel;}
return ret;
}
bool Queue::IsEmpty(){
return(!head)&&(!tail);
}
Queue::~Queue(){
while(!IsEmpty())
remove();
}
int_queue_main.cpp
#include
using namespace std;
#include "int_queue.h"
int main(){
int i=0;
Queue Q;
for(i=0;i<16;i+=3)
Q.Add(i++);
while(!Q.IsEmpty())
cout<
return 0;
}
No comments:
Post a Comment