1.单链表的后插(画示意图)
head = &a;//通过画示意图可判断为后插法
a.next=&b;
b.next=&c;
c.next=NULL;
完整代码如下:
#include<stdio.h>
/*
01 构建链表
02 初始化链表 注意头节点 直接赋值
03 输出链表
*/
struct stu{//构建并初始化链表
int num;
float score;
struct stu *next;
};
void creat(stu &a,stu &b,stu &c)//后插法实现
{
stu *head;
head = &a;
a.next=&b;
b.next=&c;
c.next=NULL;
do{
printf("student number: %d score:%f\n",head->num, head->score);
head = head->next; //head->next = head
}while(head);
}
int main(){
struct stu a, b, c, *head;
a.num =1;
a.score = 89;
b.num = 2 ;
b.score = 98;
c.num = 3;
c.score = 99;
creat(a,b,c);
return 0;
}
2.单链表的前插
head = &c;//前插法实现
b.next=&c;
head = &b;
a.next=&b;
head = &a;
完整代码如下:
#include<stdio.h>
/*
01 构建链表
02 初始化链表 注意头节点 直接赋值
03 输出链表
*/
struct stu{//构建并初始化链表
int num;
float score;
struct stu *next;
};
void creat(stu &a,stu &b,stu &c)//前插法实现
{
stu *head;
head = &c;
b.next=&c;
head = &b;
a.next=&b;
head = &a;
do{
printf("student number: %d score:%f\n",head->num, head->score);
head = head->next; //head->next = head
}while(head);
}
int main(){
struct stu a, b, c, *head;
a.num =1;
a.score = 89;
b.num = 2 ;
b.score = 98;
c.num = 3;
c.score = 99;
creat(a,b,c);
return 0;
}