创建单链表,存储4个学生信息(年龄,分数,姓名)。
1、建立学生结构体数组,存放4个学生信息,循环调用插入函数,建立整表
2、任意位置插入一个新学生。变量e是学生结构体变量。
3、任意位置删除一个学生。
4、单链表逆置后将学生信息输出。
主函数(main.c)
#include"link.h"
int main(int argc, const char *argv[])
{
Plink L=get_h();
stu students[4] = {
{"王", 20, 89},
{"刘", 22, 92},
{"孙", 19, 85},
{"李", 21, 88}
};
stu New={"陈",22,78};
int i;
//尾插法
for(i=0;i<4;i++)
{
tail_insert(L,students[i]);
}
//链表遍历
node_output(L);
printf("任意位置插入\n");
//任意位置插入
insert_any_pos(L,4,New);
node_output(L);
//任意位置删除
printf("任意位置删除\n");
dele_any_pos(L,3);
node_output(L);
printf("逆置\n");
node_reverse(L);
node_output(L);
free(L);
return 0;
}
link.h
#ifndef __LINK_H__
#define __LINK_H__
#include<myhead.h>
typedef struct
{
char name[20];
int age;
int score;
}stu;
typedef struct node
{
union //联合体,每次使用联合体中的一个数据
{
int len;//头节点,链表长度
stu data;
};
struct node *next;//节点指针域,存储下一节点地址
}Link,*Plink;
Plink get_h();
int node_output(Plink L);
int tail_insert(Plink L,stu e);
int insert_any_pos(Plink L,int pos,stu e);
int dele_any_pos(Plink L,int pos);
int node_reverse(Plink L);
#endif
link.c
#include"link.h"
Plink get_h()
{
Plink p=malloc(sizeof(Link));
if(p==NULL)
{
printf("申请头结点失败\n");
return NULL;
}
p->len=0;
p->next=NULL;
return p;
}
int node_output(Plink L)
{
if(L==NULL || L->len==0)
{
printf("单链表不存在\n");
return -1;
}
int i;
Plink t=L;//指向头指针
for(i=0;i<L->len;i++)
{
t=t->next;
printf("%s\t%d\t%d\t",t->data.name,t->data.age,t->data.score);
printf("\n");
}
return 0;
}
int tail_insert(Plink L,stu e)
{
int i;
if(L==NULL)
{
printf("单链表不存在\n");
return -1;
}
//尾插法
Plink t=L;
for(i=0;i<L->len;i++)
{
t=t->next;//将t指向最后一个节点
}
Plink p=malloc(sizeof(Link));
p->data=e;
t->next=p;
p->next=NULL;
L->len++;
return 0;
}
int insert_any_pos(Plink L,int pos,stu e)
{
int i;
Plink t=L;
for(i=1;i<pos;i++)
{
t=t->next;
}
Plink p=malloc(sizeof(Link));
p->data=e;
p->next=t->next;
t->next=p;
L->len++;
}
t->next=t->next->next;
L->len--;
运行结果:
王 20 89
刘 22 92
孙 19 85
李 21 88
任意位置插入
王 20 89
刘 22 92
孙 19 85
陈 22 78
李 21 88
任意位置删除
王 20 89
刘 22 92
陈 22 78
李 21 88
逆置
李 21 88
陈 22 78
刘 22 92
王 20 89