关于建立动态链表的问题
先上代码程序代码:
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #define LEN sizeof(struct student) struct student { int num; float score; struct student *next; }; int n; int main(void) { struct student *creat(void); //声明建立链表的函数 void print(struct student *); //声明输出链表的函数 struct student *head; head = creat(); //调用create函数 print(head); //调用print函数 system("pause"); return 0; } struct student *creat(void) //定义建立链表的函数 { struct student *head = NULL, *p1 = NULL, *p2 = NULL; p1 = p2 = (struct student *)malloc(LEN); printf("please input the num : "); scanf("%d", &(p1 -> num) ); printf("please input score : "); scanf("%f", &(p1 -> score)); n = 0; while (0 != p1 -> num) { n++; if (1 == n) { head = p1; } else { p2->next = p1; } p2 = p1; p1 = (struct student *)malloc(LEN); printf("please input the num : "); scanf("%d", &(p1->num)); printf("please input score : "); scanf("%f", &(p1->score)); } p2->next = NULL; return head; } void print(struct student *head) //定义输出链表的函数 { struct student *p; p = head; while (0 != p -> num) { printf("成员%d的分数为%f\n", p -> num, p -> score); p = p->next; } }
每次输出完后,都会出现这个对话框。忘了说题目要求如果输入的num的值为0时,则表示建立链表的过程结束,该节点不连接到链表中
,
[ 本帖最后由 firewater 于 2015-3-16 19:09 编辑 ]