分别使用了从头插入以及从尾部插入
#include <stdio.h>
#include<stdlib.h>
struct student{
int yu;
int shu;
int ying;
struct student *next;
};
void printlink(struct student *head){ //先while遍历时printf出来
struct student *p;
p = head;
while(p != NULL){
printf("%d %d %d\n",p->yu,p->shu,p->ying);
p = p->next;
}
putchar('\n');
}
//头一直都是最新的节点 新节点作为头 头插法
struct student* insertfromhead(struct student *head,struct student *new){
if(head == NULL){
head = new;
}else{
new->next = head;
head = new;
}
return head;
}
//尾插法
struct student* insertbeind(struct student *head,struct student *new){
struct student *p = head;
if(p == NULL){
head = new;
return head;
}
while(p->next != NULL){
p = p->next;
}
p->next = new;
return head;
}
struct student* createlink(struct student *head){
struct student *new;
while(1){
new = (struct student* )malloc(sizeof(struct student));
new->next=NULL;
printf("input your fengshu\n");
scanf("%d %d %d",&(new->yu),&(new->shu),&(new->ying));
if(new->yu == 0){ //如果输入0就直接返回
printf("0 quit\n");
free(new);
return head;
}
head = insertbeind(head,new); //选择要使用的插入方式
}
}
int main()
{
struct student *head = NULL;
head = createlink(head);
printlink(head);
//可以与别的结构体连接
struct student t10 = {11,22,33,NULL};
head = insertfromhead(head,&t10);
printlink(head);
return 0;
}