简体   繁体   English

在将元素推送到队列之前增加队列的大小如何让我出错而相反的工作正常?

[英]How incrementing the size of a queue before pushing an element to a queue gets me an error and the opposite works fine?

Like I said if I put q->size++ (in push_queue function) before the if statement which contains the code of pushing an element to the queue the running of the program crashes however if I put the line after the if statement it works perfectly even though there is nothing related to the size of the queue, here is the code:就像我说的,如果我将 q->size++(在 push_queue 函数中)放在包含将元素推送到队列的代码的 if 语句之前,程序的运行会崩溃,但是如果我将行放在 if 语句之后,它甚至可以完美运行虽然与队列的大小无关,但这里是代码:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct queue_node
{
    int value;
    struct queue_node *next;
};

typedef struct queue_node queue_node;
struct queue
{
    queue_node *front ;
    queue_node *back ;
    int size;
};
typedef struct queue queue;


queue * create_queue()
{
    queue * q = malloc(sizeof(queue));
    q->back = q->front = NULL;
    q->size = 0;
    return q;
}
bool empty(queue *q)
{
    return (q->size == 0) ;
}

void push_queue(queue *q , int value)
{
    queue_node *qn = malloc(sizeof(queue_node));
    qn->next = NULL;
    qn->value = value;
    q->size++;

        if (empty(q))
    {
        q->back = q->front = qn;

    }
    else
    {
        q->back->next = qn;
        q->back = qn;

    }

}

int pop_queue(queue *q)
{
    if (empty(q))
    {
        printf("vide");
        return 0;

    }
        int value = q->front->value;
        queue_node *qn = q->front;
        q->front = q->front->next;
        free(qn);
        q->size--;
        return value;
}


int main ()
{
    queue *q = create_queue();
    push_queue(q,5);
    push_queue(q,9);
    push_queue(q,7);

    while (!empty(q))
        printf("%d\t",pop_queue(q));
    free(q);
    return 0;
}

push_queue is first checking if the queue is empty. push_queue首先检查队列是否为空。 empty uses size . empty使用size If you increment size before checking empty , empty will always be false.如果在检查empty之前增加 size , empty将始终为 false。 On the first push q->back will be null and q->back->next will segfault.在第一次推送时q->back将是 null 并且q->back->next将出现段错误。

Note: since this is a FIFO (First In First Out) queue , "pop" is the wrong term.注意:由于这是一个FIFO(先进先出)队列,因此“pop”是错误的术语。 "push" and "pop" are associated with stacks and LIFO queues . “push”和“pop”与堆栈和 LIFO 队列相关联。 Consider "enqueue" and "dequeue".考虑“入队”和“出队”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM