something is wrong with my dequeue function. When i try to output the value that's about to get deleted i get garbage on the console window. the enqueue function works fine.

class Queue
{
private:
	int value;
	Queue *next;
public:
	void dequeue();
	void enqueue (int num);
};

Queue *head=NULL;

void Queue::dequeue()
{
	Queue *temp1,*temp2;
	if(head==NULL)
		cout<<"Can’t dequeue, the Queue is empty" << endl;
	else
	{
		temp1=head;
		temp2=temp1;
		while(temp1->next!=NULL)
		{
			temp2=temp1;
			temp1=temp1->next;
		}
		if(temp1==temp2)
		{
			cout<<temp1->value<<", ";
			head=NULL;
		}
		else
		{
			cout<<temp1->value<<", ";
			temp2->next=NULL;
			delete temp1;
		}
	}
}

void Queue::enqueue (int num)
 {
	 Queue *temp;
	 temp = new Queue;
	 temp->value;
	 cout << "print" << num << endl;
	 if (head == NULL)
	 {
		 temp->next=NULL;
		 head = temp;
	 }
    else
	{
		temp->next=head;
		head=temp;
	}
}

>> the enqueue function works fine.

How do you know?


Lines 50 and 55. I see the same line in both paths of the if-elese statment, which suggests either one is incorrect or the lines should be removed from the if-statement and placed after it since both paths cause identical behavior for those lines. I see a line 45 that appears to do nothing. I see a parameter to that function that is unused except to print it out.

Edited 4 Years Ago by VernonDozier: n/a

I would suggest reading over this guide here: http://login2win.blogspot.com/2008/07/c-queues.html

you're on your way to making your queue work. As to your enqueue, you never actually set the value you pass to the new node you're making (hence the garbage output). This right here needs to be:

temp->value = num;

On your cout statement, instead of printing out num, print out temp->value. That way you know you are passing the values correctly.

Anyway think of a queue like a bunch of plates on top of each other waiting to be washed. You have the head (bottom) and a tail (top). you don't take items from the head (bottom) or else the whole stack of plates falls :P

>> Anyway think of a queue like a bunch of plates on top of each other waiting to be washed. You have the head (bottom) and a tail (top). you don't take items from the head (bottom) or else the whole stack of plates falls


Bad analogy. You also don't insert the dirty plate at the bottom or all the plates fall, but in a FIFO queue, which I assume the OP is designing, if you take from the top, you have to insert at the bottom. The analogy is better for a LIFO, or a stack. Plates are inserted at the top and taken from the top.

This article has been dead for over six months. Start a new discussion instead.