2013-05-04 98 views
0

我的程序有问题。我创建了一个链接列表队列,当我用我的delQueue函数清除队列时,我的队列消失了,我再也不能推动任何东西了。链表C编程队列

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

这里是我的代码:

#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"); 
} 
+1

当你'推'你正在更新'前'。当你推动时不应该更新'后部'?队列先进先出...所以当你推动时,'后部'指针应该被更新。 – Bill 2013-05-04 02:16:18

+0

非常感谢大家,您一直非常乐于助人。我非常感谢我在这里收到的所有帮助,并且我肯定了解了很多关于队列的知识。比你再次。上帝保佑你们所有人 – user2133160 2013-05-04 02:43:47

+0

你应该接受你认为最好回答你的问题的答案;) – Bill 2013-05-04 02:51:58

回答

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 */ 
} 
+0

我的队列现在存在,但我不能添加任何东西,它不会推入任何东西,但是队列在那里并且是空的。 – user2133160 2013-05-04 02:28:18

+0

看到更新,也许这是因为你没有重置'front'。 – perreal 2013-05-04 02:31:32

+0

由于它是一个队列,我更喜欢从前面删除,正如我的答案中所给出的。否则你失去了一个队列的含义,先进先出 – Bill 2013-05-04 02:35:55

0

您正在看的“变种”你释放后(当你周围的循环再次去)。你是否想在delQueue()的循环中分配“var = buf”?

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

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

    return count; 
    } 

既然是排队,我宁愿从前面删除元素,而不是后面。

+0

它的工作完美,但我似乎无法看清计数我删除了多少项目。我会在哪里放? – user2133160 2013-05-04 02:35:04

+0

在代码中添加了计数:)并且函数现在返回计数... – Bill 2013-05-04 02:39:21

0

你必须在delQueue()

后部=前面= NULL的末尾添加以下行;