【问题标题】:Queue stuck in loop队列卡在循环中
【发布时间】:2019-02-28 16:10:31
【问题描述】:

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

#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;
}

【问题讨论】:

标签: c algorithm gcc queue


【解决方案1】:

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

【讨论】:

  • 但是为什么它每次都像rear->next =rear那样创建循环
  • @Dau 我不确定你的意思,但是将if (rear == temp) { rear == NULL; } 添加到deQueue 应该可以解决问题。
  • @Dau free(deQueue()); 之后的下一个 enQueue(); 可能正在分配刚刚释放的同一块内存并且 rear 变量仍然指向(因为你没有设置它到NULL)。所以rear-&gt;next = temp; 最终指向自己。
  • 谢谢@IanAbbott 实际上我已经解决了这个问题,但无法理解这种行为。感谢您的评论和解释。
猜你喜欢
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
  • 2014-01-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
相关资源
最近更新 更多