Home > Software engineering >  C \C | Link | Queue | Hyperlink
C \C | Link | Queue | Hyperlink

Time:11-19

when i choose at Queue insert value ( example 1 ), then i call remove_Queue, and then i try to print_Queue, but in terminal i see value -572662307

code:


const int MAX_QUEUE = 10;

typedef int Item;

struct Queue {
    Item value; 
    Queue* next;
};

Queue* front;
Queue* back;
Queue* tmp; 
bool remove_Queue(Item& i,Queue* front, Queue* back)
{
    if (front == NULL) return false;
    i = front->value;
        Queue* tmp = front;     
        front = front->next;
        delete tmp; 
    if (x == 0) back = NULL // x-- in main, when i call this function
    return true;

}

I hope someone can explain why i see this value when i delete just 1 value in my Queeu

CodePudding user response:

You have global variables (that's bad), and you have local variables named the same as your global variables (that's worse) and you are expecting changes to local variables to be reflected outside of the local scope (that's plain wrong).

It's not completely clear what you are trying to do. I'm going to go down the global variable route (which is bad as I said above, but perhaps easier to understand).

I'm going to use the global variables as global variables, this means removing them as parameters to your remove_Queue function, but I'm going to change tmp to a local variable, which is what it should be.

const int MAX_QUEUE = 10;

typedef int Item;

struct Queue {
    Item value; 
    Queue* next;
};

Queue* front;
Queue* back;

As you can see tmp has gone.

bool remove_Queue(Item& i)
{
    if (front == NULL)
        return false;
    i = front->value;
    Queue* tmp = front;     
    front = front->next;
    delete tmp;
    if (front == NULL) // is the queue empty?
        back = NULL;
    return true; 
}

As you can see front and back are no longer parameters, so changes to them will affect the global variables declared above, instead of the local variables you had before. I also simplified this function, removing the parts I didn't understand. I also added a check for an empty queue, presumably then back should also be set to NULL.

  • Related