我编写了一个程序作为行管理器,但是当显示人名时,它将最后添加的人设置为所有其他人。我该怎么修理它?如果我改变struct
中的信息,它会出错;但是,如果有人能帮助我,我会很高兴的。
#include<stdio.h>
#include<stdlib.h>
struct node {
int priority;
int info;
struct node *link;
} *front = NULL;
void insert(char person[20], int person_priority);
int del();
void display();
int isEmpty();
int main() //!! fixed
{
int choice, person_priority;
char person[20];
while (1) {
printf("1.Insert Personn");
printf("2.Attend Clientn");
printf("3.Show Queuen");
printf("4.Exitn");
printf("Type choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Type persons name:");
scanf("%s", &person);
printf("Its Priority:n1 Pregnantn2 Oldern3 Standard: ");
scanf("%d", &person_priority);
insert(person, person_priority);
system("cls");
break;
case 2:
system("cls");
printf("Person was attended", del());
break;
case 3:
system("cls");
display();
break;
case 4:
exit(1);
default:
printf("Invalid Choicen");
} /*end of switch */
} /*end of while */
return 0; //!! fixed
} /*end of main() */
void insert(char person[20], int person_priority)
{
struct node *tmp, *p;
tmp = (struct node *) malloc(sizeof(struct node));
if (tmp == NULL) {
printf("No Memory availablen");
return;
}
tmp->info = person;
tmp->priority = person_priority;
/*Starting list*/
if (isEmpty() || person_priority < front->priority) {
tmp->link = front;
front = tmp;
}
else {
p = front;
while (p->link != NULL && p->link->priority <= person_priority)
p = p->link;
tmp->link = p->link;
p->link = tmp;
}
} /*end of insere() */
int del()
{
struct node *tmp;
int person;
if (isEmpty()) {
printf("Empty Queuen");
exit(1);
}
else {
tmp = front;
person = tmp->info;
front = front->link;
free(tmp);
}
return person;
} /*end of del() */
int isEmpty()
{
if (front == NULL)
return 1;
else
return 0;
} /*end of emtpy verification (isEmpty()) */
void display()
{
struct node *ptr;
ptr = front;
if (isEmpty())
printf("Empty Queun");
else {
printf("Line :n");
printf("Priority Namen");
while (ptr != NULL) {
printf("%5d %5sn", ptr->priority, ptr->info);
ptr = ptr->link;
}
printf("nnn");
}
}
您的struct节点有一个名为"info"的元素,其类型为int。每次添加一个人时,使用scanf()将该人的姓名读入字符数组,然后将该字符数组的地址传递给insert(), insert()将地址存储在整数"info"中。你分配的每个struct node
,都存储了相同变量的相同地址。每次scanf()都在覆盖相同的内存。
你的结构节点应该有一个元素char info[20]
,当你创建一个新的节点时,你应该把这个人的名字strcpy()
到tmp->info。
还需要注意的是,将变量交替作为char*类型和int类型处理的方式会导致未定义的行为。