定义学生信息,包括学生性名(name)与年龄(age),定义函数:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct LinkList{
char name[10];
int age;
struct LinkList *next;
}Student;
初始化数据表元素,创建InitList()函数
1、分配数据表空间
2、指定头节点的下一节点为NULL.
注意:如果不使用二重指针则无法对地址操作。初始化时必须要把地址传输过去。
/初始化
void InitList(Student* *sl){
*sl=(Student*)malloc(sizeof(Student)); //分配空间
(*sl)->next=NULL; //初始化
}
添加链表数据元素,创建InsertE()进行赋值操作。创建一个伪节点指向头节点和一个新节点(插入节点)并为新节点分配空间。循环遍历数据表使得伪节点指向最后一个节点并把新节点赋值给最后一个节点并赋值为空值。
//链表元素插入
void InsertE(Student* sl,char name[],int age){
Student* temp = sl;
Student* node_new=(Student*)malloc(sizeof(Student));//创建新节点,即插入节点并分配空间
while(temp->next!=NULL){
temp=temp->next;//寻找尾节点的位置
}
temp->next=node_new;//头节点的下一个节点指向插入节点
node_new->next=NULL;//插入节点的后一个节点为空
//赋值操作
strcpy(node_new->name,name);
node_new->age=age;
}
插入操作的主函数:
int main(){
Student* sl;
InitList(&sl);
InsertE(sl,"张三",18);
InsertE(sl,"李四",19);
InsertE(sl,"王五",18);
InsertE(sl,"赵六",20);
}
遍历函数:
//链表遍历输出
void Display(Student* sl){
Student* dis = sl->next;
printf("姓名:\t年龄:\n");
while(dis!=NULL){
printf("%s\t%d\n",dis->name,dis->age);
dis=dis->next;
}
printf("\n");
}
插入结果: