请教一个链表的数据输入的问题
#include <stdio.h>#include<stdlib.h>
#define LEN sizeof(struct Student)
struct Student
{
long num;
float score;
struct Student *next;
};
int n;
struct Student *creat() //输入函数
{
Student *head;
Student *p1, *p2;
n = 0;
p1 = p2 = (Student*)malloc(LEN);
/*scanf_s("%ld %f",&p1->num,&p2->score);*/ //为什么使用这种格式输入,程序就会出错呢?
printf("input the num: ");
scanf_s("%ld", &p1->num);
printf("input the score: ");
scanf_s("%f", &p1->score);
head = NULL;
while (p1->num != 0)
{
n ++;
if (n == 1)
{
head = p1;
}
else
p2->next = p1;
p2 = p1;
p1 = (Student*)malloc(LEN);
/*scanf_s("%ld %f", &p1->num, &p2->score);*/ //为什么使用这种格式输入,程序就会出错呢?
printf("input the num: ");
scanf_s("%ld", &p1->num);
printf("input the score: ");
scanf_s("%f", &p1->score);
}
p2->next = NULL;
return (head);
};
void print(Student *head) //输出函数
{
Student *p;
printf("\nNow,These %d record are:\n", n);
p = head;
if (head!=NULL)
{
do
{
printf("%ld %5.1f\n", p->num, p->score);
p = p->next;
} while (p!=NULL);
}
}
struct Student *del(struct Student *head, long num) //删除指定节点
{
struct Student *p1, *p2=NULL;
if (head == NULL)
{
printf("\nlist null!\n");
return(head);
}
p1 = head;
while (num != p1->num&&p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (num == p1->num)
{
if (p1 == head)head = p1->next;
else p2->next = p1->next;
printf("delete:%ld\n", num);
n = n - 1;
}
else
printf("%ld not been found!\n", num);
return head;
}
int main()
{
Student *head;
head = creat();
print(head);
printf("Please input the num to deleat:");
scanf_s("%d", &n);
print(del(head, n));
return 0;
}
[/code]
发现问题了。。。。
注释掉的输入代码中p1粗心的写成了p2
[此贴子已经被作者于2018-3-19 01:32编辑过]