关于创建链表,开始的流程图如下,先建立一个节点,然后p,q指针都指向该节点。将p指针赋给head指针,然后赋值,令q指向p后(在后续中是移位到p新开的节点之前),p指针再开辟一个新的节点。然后p与q建立联系,即q->next指向p。如此往复循环,直到最后一个结束循环,记得将p->next赋值为NULL。
#include<stdio.h>
#include<stdlib.h>
struct Student{
int num;
int score;
struct Student *next;
};
struct Student *create(int population){
struct Student *p,*q,*head;
int n=0; int i;
p=q=(struct Student *)malloc(sizeof(struct Student));
head=NULL;
for(i=0;i<population;i++){
n+=1;
if(n==1) head=p;
else q->next=p;
scanf("%d %d",&p->num,&p->score);
q=p;
p=(struct Student *)malloc(sizeof(struct Student));
}
q->next=NULL;
return (head);
}
void print(struct Student *head){
struct Student *temp;
temp=head;
if(head==NULL) printf("Error operation!\a");
else{
do{
printf("Num= %d, Score= %d\n",temp->num,temp->score);
temp=temp->next;
}while(temp!=NULL);
}
}
int main(){
struct Student *head;
int population;
printf("Please input number of students: ");
scanf("%d",&population);
head=create(population);
print(head);
return 0;
}
|