Hi,
There is short explanation of queue at cplusplus.com site which tells that queue should contain front() and back() functions.
As I have tested in VC++, if I use queue from <queue> and call any of these functions for an empty queue, program crashes.
Could this problem be solved by simply adding a throw, in case when queue is actually empty, so front and back would throw an exception which'd be caught by try block?
( of course I am talking about queue, one would create, as I have done)
Here is my simple solution of this problem.
struct Exception{
const char* error;
Exception(const char* a):error(a){};
};
struct elem{
int data;
elem* next;
};
class queue{
elem* head;
elem* last;
elem* current;
int size;
public:
queue();
int& front();
int& back();
void pop();
void push(int);
int Size();
bool empty();
};
bool queue::empty(){
if(head==NULL)
return true;
return false;
}
queue::queue(){
head=0;
size=0;
}
void queue::push(int x){
current=new elem;
current->data=x;
current->next=NULL;
if(head==NULL){
head=current;
last=head;
}
else if(head!=NULL){
last->next=current;
last=current;
}
}
void queue::pop(){
if(head!=NULL){current=head;
head=current->next;
}
}
int& queue::front(){
if(head!=NULL)
return head->data;
else throw Exception("Queue is empty.");
}
int& queue::back(){
if(last!=NULL)
return last->data;
else throw Exception("Queue is empty.");
}
int queue::Size(){
size=0;
current=head;
while(current!=NULL){
size++;
current=current->next;
}
return size;
}
Do you have any critics about this solution, if you do, what is it, and what's your better solution?
Thanks.