Hello, I am trying to create a singly linked list implementation of a stack, but I keep getting strange errors that have to do with my dequeue function, but I have no idea what I could be doing wrong, my compiler keeps pointing to the line "frontNode = frontNode->next;" but I can't figure out why.
#ifndef _QUEUE_H_
#define _QUEUE_H_
class Queue
{
public:
//The nodes that make up the queue
class QueueNode
{
public:
int data;
QueueNode *next;
};
//Constructs an empty queue
Queue();
//Destructor
~Queue();
//Returns true if the queue is empty
bool isEmpty();
//Returns the value at the front of the queue
int front();
//Adds a new value to the end of the queue
void enqueue(int newData);
//Deletes the data at the front of the queue
void dequeue();
//Returns the current size of the queue
int getSize();
private:
//Keeps track of the front of the queue
QueueNode *frontNode;
//Keeps track of the rear of the queue
QueueNode *rearNode;
int size;
};
#endif
Basically every time I try to run my main QueueTest program, the whole program breaks in a different place of the same while loop, never quite getting to the end. But whenever I comment out the call to the dequeue, it runs through fine (except for the stuff that I need the dequeue functional for). I'm pretty sure I'm getting some kind of segmentation fault but have no idea why.
It would be helpful to post the actual error. I see in your destructor that you are deleting your node members without checking to see if they aren't NULL.
Also, anytime you access one of your pointers, make sure they point to somewhere (hopefully a valid) place.
If you call dequeue on an empty Queue, you're going to dereference a null pointer. Also, your destructor needs work -- front and rear will not always be the only nodes allocated, and if front == rear, you're going to be deleting the same node twice.