链表输出最后一行数据总是乱码
这个输出链表的函数有什么问题吗
void display(student* head)
{
student* p = head;
if (!p)
{
printf("链表为空!\n");
exit(1);
}
else
while (p)
{
printf("%-20s %-12lld\n", p->name, p->nmber);
p = p->next;
}
}
这里是完整代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
typedef struct stu
{
long long nmber;
char name[10];
struct stu* next;
}student;
student* init()
{
return NULL;
}
student* get_num(student* head)
{
int flag;
head = (student*)malloc(sizeof(student));
student* q, * p = head;
p->next = NULL;
printf("请输入第一个同学的数据(姓名、手机号)\n");
char nam[10];
int i = 2;
flag = scanf_s("%s", nam,10);
while (i<3)
{
scanf_s("%lld", &p->nmber);
strcpy_s(p->name, nam);
printf("请输入第%d个同学的信息:\n", i++);
flag = scanf_s("%s", nam,10);
if (flag == 1)
{
q = (student*)malloc(sizeof(student));
q->next = NULL; p->next = q; p = q;
}
else break;
}
return head;
}
student* insert(student* head, int position)
{
int flag;
char nam[10];
student* p = head, * q = NULL;
if (position < 1)
{
printf("输入位置有误!");
exit(1);
}
q = (student*)malloc(sizeof(student));
printf("请输入增加的学生的姓名、手机号:\n");
flag = scanf_s("%s", nam,10);
scanf_s("%lld", &q->nmber); q->next = NULL;
if (flag == 1)
strcpy_s(q->name, nam);
if (position == 1)
{
if (!p)
{
printf("通讯录为空!\n");
exit(1);
}
else
{
q->next = p; return q;
printf("插入成功!\n");
}
}
else
{
for (int i = 1; p; i++)
{
if (i + 1 == position)
{
q->next = p->next;
p->next = q;
printf("插入成功!\n");
return head;
}
}
if (!p)
{
printf("未找到增加的位置!\n");
return head;
}
}
}
student* del(student* head, int position)
{
student* p = head, * q = NULL;
if (!p)
{
printf("删除失败,链表为空!\n");
}
if (position < 1)
{
printf("删除失败,输入的位置有误!\n");
return head;
}
if (position == 1)
{
if (p->next)
{
q = p;
head = p->next;
free(q);
return head;
}
printf("删除成功!\n");
}
for (int i = 1; p; i++)
{
if (i + 1 == position && p->next)
{
q = p->next;
p->next = p->next->next;
free(q);
return head;
}
p = p->next;
printf("删除成功!\n");
}
if (!p)
{
printf("删除失败,该位置处无元素!\n");
}
}
void display(student* head)
{
student* p = head;
if (!p)
{
printf("链表为空!\n");
exit(1);
}
else
while (p)
{
printf("%-20s %-12lld\n", p->name, p->nmber);
p = p->next;
}
}
int main()
{
int order, position;
student* head = init();
head = get_num(head);
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
getchar();
loop:
printf("—————————请输入操作—————————\n1.插入一个新信息,2.删除一个信息,3.输出所有信息 :\n");
getchar();
scanf_s("%d", &order);
switch (order)
{
case 1:
printf("请输入要插入的节点位置:\n");
scanf_s("%d", &position);
head = insert(head, position);
break;
case 2:
printf("请输入要删除节点的值:\n");
scanf_s("%d", &position);
head = del(head, position);
break;
case 3:
printf("输出结果为:\n");
display(head);
break;
default:printf("ERROR\n");
}
goto loop;
}