[英]Queue of linked list C programming
我的程序有問題。 我已經創建了一個鏈表列表隊列,當我使用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");
}
釋放它后,您正在查看“ var”(當您再次繞過循環時)。 您是否要在delQueue()的循環中分配“ var = buf”?
另外,不要忘記在push()例程中檢查malloc()的返回是否為NULL。 即使這只是一個小型學習程序,您也應該學會始終檢查...
void delQueue()
{
while(rear != NULL) {
struct Node* var=rear->next;
free(rear);
count = count + 1;
rear = var; /* update rear */
}
front = NULL; /* clear the front */
}
int delQueue()
{
int count = 0;
while ( front != NULL )
{
struct Node * temp = front;
front = front -> next;
free (temp);
count++;
}
rear= NULL;
return count;
}
由於它是一個隊列,因此我寧願從前面而不是后面刪除元素。
您必須在delQueue()的末尾添加以下行
后=前= NULL;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.