Domanda

I have declare a struct like below:

struct example
{
      // some element here
      struct example *next;
};
struct example *head;

Suppose I have alredy made a queue from "example" struct and now I want to move out the head element (surely, after move first element in queue out I have to delete it out of queue). I have delete code like this:

void delete()
{
    struct example *temp = malloc (sizeof(struct example) * 1);
    temp = head;
    head = head->next;
    free(temp);
}

And my question is function "delete" do the jobs:

  1. Delete first element in queue and make next element be head of new queue

or 2. It's not delete first element in queue but make head = head->next and delete "temp" pointer and "the old head" still exist somewhere

È stato utile?

Soluzione

You are in fact appropriately setting head to the next item in the queue and deleting the old head. However, for what appears to be no reason, you are using malloc() to create memory which you then lose the only pointer to when you overwrite temp on the next line. You should initialize temp to head. There is no need to malloc() memory in a delete() function. If you did need malloc(), note that * 1 is redundant and unnecessary.

Also, what will happen if your queue is empty and head is NULL? Think about that.

Whether your queue will work or not remains to be seen since you will also need a tail pointer to know where to add new items to the queue.

Additionally, I would avoid naming functions delete() since it may be confused for the C++ keyword delete. remove() would be more appropriate.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top