写一个函数建立一个3名学生数据的单向动态链表
#include
#include
#include
#define LEN (sizeof(struct Student))
typedef struct Student
{
long num;
float score;
struct Student* next;
}st;
int main()
{
st* creat(int n);
void print(st * head);
int k;
st* head;
printf("输入想要创建的结点数:\n");
scanf("%d", &k);
head = creat(k);
print(head);
return 0;
}
st* creat(int n) //尾插法建立链表的函数
{
st* node, * end; //定义新结点node, 尾结点end
st* head; //头结点
head = (st*)malloc(LEN); //给头结点开辟空间
if (head == NULL)
{
printf("out of memory, the request failed!\n"); //内存不足,申请失败
exit(-1);
}
memset(head, 0, LEN);
end = head; //头尾地址一致,即头结点就是尾结点,为空表
for (int i = 0; i < n; i++)
{
node = (st*)malloc(LEN); //为普通结点申请空间
if (node == NULL)
{
printf("out of memory, the request failed!\n");
exit(-1);
}
memset(node, 0, LEN);
scanf("%ld %f", &node->num, &node->score); //给数据域赋值
end->next = node; //让上一个结点的数据域指向当前结点
end = node; //指向新的尾结点
}
end->next = NULL; //尾结点最后的指针域置空
return head;
}
void print(st* head) //打印链表函数
{
st* p = head; //p指向头结点
p = p->next; //因为头结点的数据域一般不存数据,所以让p指向头结点后面的一个结点
printf("the data for the three students are\n");
while (p != NULL)
{
printf("%5ld\t%5.2f\n", p->num, p->score);
p = p->next; //每输出一个结点的数据域,就让p往后移
}
}
输出不了