链表C编程的队列

时间:2013-05-04 02:03:39

标签: c linked-list queue

我的程序有问题。我创建了一个链接列表队列,当我用delQueue函数清除队列时,我的队列消失了,我再也无法推送任何内容了。

我该如何解决这个问题?除非我从队列中删除所有内容,否则我的推送功能正常。

这是我的代码:

#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 个答案:

答案 0 :(得分:0)

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

另外,不要忘记在push()例程中检查malloc()返回NULL。即使这只是一个小型的学习计划,你也应该学会一直检查......

答案 1 :(得分: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 */
}

答案 2 :(得分:0)

 int delQueue()
    {
   int count = 0;
    while ( front != NULL )
    {
    struct Node * temp = front;
    front = front -> next;
    free (temp);
    count++;
    }
    rear= NULL;

    return count;
    }

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

答案 3 :(得分:0)

你必须在delQueue()

的末尾添加以下行

rear = front = NULL;