0

I have a problem with my program. I have created a queue of linked lists, and when I clear my queue with my delQueue function, my queue disappears, and I can't push anything in anymore.

How can I fix this? My push function works fine unless I delete everything from my queue.

Here is my code:

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

int count = 0;

struct Node
{
    int Data;
    struct Node* next;
}*rear, *front;

void delQueue()
{

    struct Node *var=rear;
    while(var!=NULL)
    {
        struct Node* buf=var->next;
        free(var);
        count = count + 1;

    }

}

void push(int value)
{
    struct Node *temp;
    temp=(struct Node *)malloc(sizeof(struct Node));
    temp->Data=value;
    if (front == NULL)
    {
        front=temp;
        front->next=NULL;
        rear=front;
    }
    else
    {
        front->next=temp;
        front=temp;
        front->next=NULL;
    }
}

void display()
{
    struct Node *var=rear;
    if(var!=NULL)
    {
        printf("\nElements in queue are:  ");
        while(var!=NULL)
        {
            printf("\t%d",var->Data);
            var=var->next;
        }
    printf("\n");
    } 
    else
    printf("\nQueue is Empty\n");
}
4

4 回答 4

0

释放它后,您正在查看“var”(当您再次绕过循环时)。您的意思是在 delQueue() 的循环中分配“var = buf”吗?

另外,不要忘记在 push() 例程中检查 malloc() 的返回是否为 NULL。即使这只是一个小型学习程序,您也应该学会始终检查...

于 2013-05-04T02:07:14.903 回答
0
void delQueue()
{
    while(rear != NULL) {
        struct Node* var=rear->next;
        free(rear);
        count = count + 1;
        rear = var;         /* update rear */
    }
    front = NULL; /* clear the front */
}
于 2013-05-04T02:09:06.900 回答
0

您必须在 delQueue() 的末尾添加以下行

后=前=空;

于 2013-05-04T05:23:09.563 回答
0
 int delQueue()
    {
   int count = 0;
    while ( front != NULL )
    {
    struct Node * temp = front;
    front = front -> next;
    free (temp);
    count++;
    }
    rear= NULL;

    return count;
    }

由于它是一个队列,我宁愿从前面删除元素,而不是后面。

于 2013-05-04T02:19:36.470 回答