求助大佬,关于链表输出问题:
输出最后一个name的值显示是P?
以下是在MinGW-W64-builds-4.3.5中输出的结果
//name:asd
//number:1
//是否继续(y键继续,任意键退出):n
//P?0
以下为代码部分
int count = 0;
typedef struct Node
{
char name[20];
int num;
struct Node *next;
} NO;
NO *input()
{
NO *head;
NO *p1, *p2;
head = NULL;
char pd = 'y';//判断是否继续创建链表
char ch;
p2 = (NO *)malloc(LEN);
while (pd == 'y' || pd == 'Y')
{
p1 = (NO *)malloc(LEN);
printf("name:");
scanf("%s", &p1->name);
ch = getchar();
printf("number:");
scanf("%d", &p1->num);
ch = getchar();
count++;
if (count == 1)
{
head = p1;
}
else
{
p2->next = p1;
}
p2 = p1;
printf("是否继续(y键继续,任意键退出)😊;
scanf("%c", &pd);
ch = getchar();
}
p2->next = NULL;
free(p1);
return (head);
}
int main(int argc, const char *argv[])
{
NO *pr;
pr = (NO *)malloc(LEN);
pr = input();
while (pr != NULL)
{
printf("%s\t", pr->name);
printf("%d\n", pr->num);
pr = pr->next;
}
}
删除: free(p1); 这行就可以了