首页 > 解决方案 > 队列卡在循环中

问题描述

我在 C 中实现了队列,如下所示。但它陷入了循环。如果我从中删除free()deQueue()那么它工作正常。这种行为的原因是什么。

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

struct item{

    int value;
    struct item* next;
};

struct item *front = NULL, *rear = NULL;

bool isEmpty(){

    return (front == NULL);
}

bool isFull(){

    return false;
}

bool enQueue( int value ) {

    struct item *temp = (struct item*) malloc( sizeof( struct item ) );
    if( temp == NULL ) {

        return false;
    }

    temp->value = value;
    temp->next = NULL;

    if( front == NULL ) {

        printf("Front is NULL\n");

        front = temp;
    }

    if( rear == NULL ) {

        printf("Rear is NULL\n");
        rear = temp;
    } else {

        printf("Rear Value %d \n", rear->value );

        rear->next = temp;
        rear = rear->next;

        printf("Rear Value %d \n", rear->value );
    }

    return true;
}

struct item* deQueue() {

    struct item *temp = front;
    front = front->next;

    return temp;
}

struct item* getFront(){

    return front;
}

struct item* getRear(){

    return rear;
}

void display(){

    struct item* temp = front;
    printf("\n[ ");
    while( temp ){

        printf("%d, ", temp->value);
        temp = temp->next;
    }
    printf("]\n");
}

int main(){

    enQueue(1);
    display();
    free(deQueue());
    display();
    enQueue(2);
    display();

    return 0;
}

标签: calgorithmgccqueue

解决方案


deQueue更新front但没有rear。后者在项目从其下方销毁后留下一个悬空指针。


推荐阅读