• Support PF! Buy your school textbooks, materials and every day products Here!

Destroying a queue

  • Thread starter AcecA
  • Start date
  • #1
12
0

Homework Statement


All I need is an explanation as to why the algorithm I've been given doesn't destroy the queue properly. When I use the code below, and I check if q is NULL or not, it says it isn't, and I'd like to know why. Thanks :)


Homework Equations


None, this is computer science.
Language is C with some C++ conventions, by the way

The Attempt at a Solution



Code:
typedef int Element;

struct _Queue {
     Element *elts;
     int head;
     int capacity;
     int count;
};

typedef _Queue* Queue;

void DestroyQueue(Queue q)
{
     delete[] q->elts;
     q->elts = NULL;
     q->head = 0;
     q->count = 0;
     delete q;
     q = NULL;
}
 

Answers and Replies

  • #2
33,477
5,167

Homework Statement


All I need is an explanation as to why the algorithm I've been given doesn't destroy the queue properly. When I use the code below, and I check if q is NULL or not, it says it isn't, and I'd like to know why. Thanks :)


Homework Equations


None, this is computer science.
Language is C with some C++ conventions, by the way

The Attempt at a Solution



Code:
typedef int Element;

struct _Queue {
     Element *elts;
     int head;
     int capacity;
     int count;
};

typedef _Queue* Queue;

void DestroyQueue(Queue q)
{
     delete[] q->elts;
     q->elts = NULL;
     q->head = 0;
     q->count = 0;
     delete q;
     q = NULL;
}
I see a couple of problems. Your elts member is a pointer to Element, which means it is a pointer to an int. It probably should be a pointer to a _Queue, otherwise I can't understand what is is being used for.

Normally in a queue data type, you have one member that points to another queue element, that in turn points to another queue element, and so on until the last element in the queue. The pointer in the last queue item has the value NULL, marking the end of the queue.

You can't be sitting in one element and delete all the other elements in one fell swoop. You need to traverse the queue to the next-to-last element, delete the last element, back up to the previous element, delete the one that that element is pointing to, and so on, backing you way until you get to the first item in the queue. In case you didn't follow that, you need to back your way through the queue, deleting the current last item.
 

Related Threads on Destroying a queue

Replies
6
Views
2K
Replies
1
Views
291
Replies
1
Views
687
Top