I implement a queue myself. when testing, I expect the dequeue to reutrn when the queue is empty by testing if the tail pointer point to the head node. However, the address of the head node and the one pointer point are different when the point indeed points to the head, hence the queue never stop dequeue even if there is nothing in it.
This confuse me a lot. Any suggestion on this?
thanks a lot.
//header
#ifndef QUEUE_H
#define QUEUE_H
struct node
{
int val;
struct node* next;
};
class queue
{
private:
node head;
node* tail;
public:
queue();
void enqueue(int val);
void dequeue(int& holder, bool& v);
};
#endif
// queue.cpp
#include "queue.h"
using namespace std;
queue::queue()
{
tail = &head;
}
void queue::enqueue(int val)
{
node* tmp = new node;
tmp->val = val;
if(tail == &head)
{
tail = tmp;
tmp->next = &head;
head.next = tmp;
}
else
{
node* holder = head.next;
head.next = tmp;
tmp->next = &head;
holder->next = tmp;
}
}
void queue::dequeue(int& holder,bool& v)
{
if(tail == &head)
{
v = false;
}
else
{
node* cur = tail;
tail = tail->next;
holder = cur->val;
v = true;
delete cur;
}
}
//test.cpp
#include <iostream>
#include "queue.h"
using std::cout;
using std::endl;
int main()
{
int ary[] = {1,2,3,4,5};
queue myq;
for(int i = 0;i< sizeof(ary);i++)
{
myq.enqueue(ary[i]);
}
int tmp;
bool flag;
for(int i = 0;i<=7;i++)
{
myq.dequeue(tmp,flag);
if(flag)
cout<<"number is "<<tmp<<endl;
else
cout<<"queue empty"<<endl;
}
return 0 ;
}
I could give you the exact fix, but that would teach you absolutely nothing, you’d just copy and paste that into your code and go away do something else. So I’m going to help you with a line of code to add to show what the current value of &head is, and thus help identify what the actual problem is…
Add this line to enqueue (at the top of the function) and dequeue:
It will print the name of the function and the address off head. (You may need to include iostream as well)
Pay particular attention to how many printouts you get!