实现一个将输入的学生成绩组织成单向链表的简单函数

 1 void input() {
 2     struct stud_node *q;
 3     do {
 4         q = (struct stud_node*)malloc(sizeof(struct stud_node));
 5         scanf("%d",&q->num);
 6         if ( q->num != 0){
 7             scanf("%s %d", q->name, &q->score);
 8             if ( head == NULL ) {
 9                 head = q;
10                 head->next = NULL;
11             }
12             if ( tail != NULL ) {  //为tail开辟结点
13                 tail->next = q;
14             }
15             tail = q;
16             tail->next = NULL;
17         }
18     } while ( q->num != 0);
19     
20 }
1 struct stud_node {
2     int              num;      /*学号*/
3     char             name[20]; /*姓名*/
4     int              score;    /*成绩*/
5     struct stud_node *next;    /*指向下个结点的指针*/
6 };
7 struct stud_node *head, *tail;

单向链表的头尾指针保存在全局变量headtail中。

大概固定的公式: 

struct stud_node *head, *tail, *q;  //头, 尾, 相当于用来控制的指针
q = (struct stud_node*)malloc(sizeof(struct stud_node));  //申请动态分配内存

令输入的元素用 q-> 来指向, 而后先判断head是否为空, 如果为空, 令head = q;

而后要做的就是让尾tail一直处于链表的尾部, 此处画图理解会比较好

总结来说建立链表的方法大概是这样, 死记这个大概的方法, 遇到不同的问题再见机更改就行了



猜你喜欢

转载自www.cnblogs.com/zhengxin909/p/12001326.html