#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct Student)
int n = 0;
typedef struct Student
{
int num;
int score;
struct Student *next;
}T_Student;
T_Student *create(int num, int score)
{
T_Student *p, *q, *head;
int inum;
int iscore;
if(num == 0)
{
printf("init input num error!\n");
return NULL;
}
q = (T_Student *)malloc(sizeof(T_Student));
if(q == NULL)
{
printf("malloc error!\n");
return NULL;
}
q->num = num;
q->score = score;
q->next = NULL;
head = q;
while(1)
{
scanf("%d %d", &inum, &iscore);
if((iscore == 0) || (inum == 0))
break;
p = (T_Student *)malloc(sizeof(T_Student));
if(p == NULL)
{
printf("malloc error!\n");
return NULL;
}
p->num = inum;
p->score = iscore;
p->next = NULL;
q->next = p;
q = q->next;
}
return head;
}
void print(struct Student *head)
{
struct Student *pr = head;
while(pr != NULL)
{
printf("the student num == %d, socre == %d\n", pr->num, pr->score);
pr = pr->next;
}
}
int main()
{
T_Student *pt;
pt = create(1, 1);
print(pt);
return 0;
}
最重要的一步是:
p->num = inum;
p->score = iscore;
p->next = NULL;
q->next = p;
q = q->next;
释义: 一般要动态加载一个链表,需要定义三个同样类型的指针,比如: prePtr, nextPtr, Head;
nextPtr用于不断申请新节点;
prePtr用于不断的指向最后一个节点;
Head用于指向头结点,用于返回;
q->next = p;
q = q->next;
就是用来不断的指向最后一个节点;