Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Destroying a queue

  1. Mar 8, 2010 #1
    1. The problem statement, all variables and given/known data
    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 :)

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

    3. The attempt at a solution

    Code (Text):
    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;
  2. jcsd
  3. Mar 9, 2010 #2


    Staff: Mentor

    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook