【发布时间】:2015-05-08 17:08:23
【问题描述】:
我尝试创建一个包含 2 个 int 值的队列。问题发生在插入函数中。当我尝试为 head->front->next 分配内存时程序停止。该错误仅发生在插入函数的 else 部分。
struct Patient{
int national_id;
int condition;
};
struct Node{
struct Patient *info;
struct Node *next;
};
struct Queue{
int total;
struct Node *rear;
struct Node *front;
int insert_number;
};
void insert (struct Queue *head, int natid, int cond);
void pop_min(struct Queue *head);
struct Queue *create_queue(void);
void destroy_queue(struct Queue *head);
void read_file(struct Queue *head);
void print_natid(struct Node *node);
void pop_all_elements(struct Queue *head);
void main(){
struct Queue *head;
head=create_queue();
read_file(head);
pop_all_elements(head);
destroy_queue(head);
}
struct Queue *create_queue(void){
struct Queue *head =(struct Queue*) malloc(sizeof(struct Queue));
head->total=0;
head->insert_number=0;
return head;
}
void print_natid(struct Node *node){
printf("%d ",node->info->national_id);
}
void insert (struct Queue *head,int natid, int cond){
if(head->total==0){
head->front=(struct Node*)malloc(sizeof(struct Node));
head->front->info->national_id=natid;
head->front->info->condition=cond;
head->rear=head->front;
}
else{
head->front->next=(struct Node*)malloc(sizeof(struct Node));
head->front->next->info->national_id=natid;
head->front->next->info->condition=cond;
head->front=head->front->next;
}
head->insert_number++;
head->total++;
if(head->insert_number==3){
pop_min(head);
head->insert_number=0;
}
print_natid(head->rear);
}
void pop_min(struct Queue *head){
printf("%d ",head->rear->info->national_id);
struct Node *temp=head->rear;
head->rear=head->rear->next;
free(head->rear);
free(temp);
}
void destroy_queue(struct Queue *head){
free(head);
}
void pop_all_elements(struct Queue *head){
struct Node *temp;
while(head->rear!=head->front){
print_natid(head->rear);
temp=head->rear;
free(temp);
head->rear=head->rear->next;
}
print_natid(head->rear);
free(head->rear);
}
void read_file(struct Queue *head){
FILE *fp;
int natid;
int cond;
fp=fopen("patients.txt","r");
while (fscanf(fp,"%d %d", &natid, &cond) ==2)
insert(head,natid,cond);
fclose(fp);
}
【问题讨论】:
-
total究竟代表什么? -
元素总数。
-
所以你不断地将新元素连接到同一个头部。您应该要么添加到队列的最后一个元素,而不是头部,要么从头部开始遍历列表。
-
我从 head->front 添加元素。后总是保存队列中最旧的元素。头是一次创建的。其实我没明白我的意思。
-
你在同一个地方一遍又一遍地添加元素。分析你的代码在做什么。