D
D
ddddd tttt2016-11-10 16:21:31
C++ / C#
ddddd tttt, 2016-11-10 16:21:31

How to correctly remove elements from a singly linked list?

struct QUEUE
{
    NODE* info;
    QUEUE *next;
};
NODE* take_out(QUEUE *q, int *error)
{
    QUEUE *old_item = q;    // начало очереди
    NODE *old_info = 0;
    if (q)  // если очередь не пуста
    {
        old_info = old_item->info;
        q = (q)->next;
        delete old_item;    // уничтожение элемента
        *error = 0;
    }
    else *error = 1;
    return old_info;
}
void    prefix(NODE *p)
{
    int *err=new int;
    QUEUE *queue = 0;
    while (p != 0 || !isempty(queue)){
        if (!isempty(queue))
        {
            p = take_out(queue, err);
        }
    
        while (p != 0){
            printf(" %-7d ", p->info);
            if (p->right != 0) 
                queue=append(queue,p->right);
            p = p->left;
        }
    }
}

How to make the queue memory free in the take_out function? now it doesn't work correctly and that's why the isempty function shows that the queue is not empty even though all the elements have been removed. They are labeled as ???.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rhaport, 2016-11-14
@rhaport

After calling take_out (usually called pop), where does the head of the queue point to? The queue variable points to the address that has just been freed.
or return a pointer to the new head in take_out:

QUEUE* take_out(QUEUE *q, NODE *node, int *error)
{
    QUEUE *old_item = q;    // начало очереди
    NODE *old_info = 0;
    if (q)  // если очередь не пуста
    {
        old_info = old_item->info;
        q = (q)->next;
        delete old_item;    // уничтожение элемента
        *error = 0;
    }
    else *error = 1;

    node = old_info;

    return q;


....
   queue = take_out(queue, p, err)
}

either organize the queue like
struct List;

struct List
{
    struct List *next;
    NODE *info;
};

typedef struct
{
    struct List *head;
} QUEUE;

int pop(QUEUE* q, NODE* info)
{
    int ret;

    if (q && q->head)
    {
        info = q->head->info;
        q->head = q->head->next;
        ret = 0;
    }
    else
    {
        ret = -1;
    }
}

For me the second option is better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question