returning wrong address from pop function

此生再无相见时 提交于 2019-12-02 07:54:05

You shouldn't be using "sentinel nodes"; this is pointless and very confusing. A queue can be simply represented as a QNode* to the first element. It always points to the first element; if it's NULL, the queue is empty; if element->next is NULL, it's the last element because there isn't a next one. It's very simple to work with that.

struct QueueNode {
    // stuff
    // stuff
    // stuff
    struct QueueNode* prev; // this may be optional
    struct QueueNode* next;
};
typedef struct QueueNode QNode;

void push_front(QNode** queue, QNode* pushme) {
    pushme->prev = NULL;
    pushme->next = *queue;
    (*queue)->prev = pushme;
    *queue = pushme;
}

void push_end(QNode** queue, QNode* pushme) {
    QNode* node = *queue;

    if (node) {
        while (node->next) node = node->next;
        node->next = pushme;
        pushme->prev = node;
        pushme->next = NULL;
    }
    else {
        *queue = pushme;
        (*queue)->next = (*queue)->prev = NULL;
    }
}

QNode* pop_front(QNode** queue) {
    QNode* node = *queue;

    if (node)
        *queue = node->next;

    return node;
}

QNode* pop_end(QNode** queue) {
    QNode* node = *queue;

    if (node) {
        while (node->next) node = node->next;
        if (node->prev) {
            node->prev->next = NULL;
            node->prev = NULL;
        }
        else
            *queue = NULL;
    }

    return node;
}


QNode* create_node_front(QNode** queue) {
    QNode* node = malloc(sizeof(QNode));
    push_front(queue, node);
    return node;
}

QNode* create_node_end(QNode** queue) {
    QNode* node = malloc(sizeof(QNode));
    push_end(queue, node);
    return node;
}

QNode* my_queue = NULL; // declare an empty queue
QNode* my_node = create_node_end(&my_queue); // create a new node, its already stored in the queue

I didn't test it, but it gives a general idea.

You can push with push_front() or create_node_front() (no loops, best performance) then pop with pop_end() to have a queue effect (FIFO), or pop with pop_front() to have a stack effect (LIFO).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!