刚接触链表的时候还是大一学的C语言,但那个时候基本没学,后来想着要为以后考虑一下,开始从头学。这是在学链表的时候写的,看了很多别人的代码。写的不是很好,欢迎各位指教。
#include<stdio.h>
#include<stdlib.h>
struct Stu
{
char name[6];
float score;
struct Stu* next;
};
int number = 1;
Stu* Creat()//创建动态链表
{
int i = 1;//当输入i为0时停止输入
Stu* head, * p1, * p2;
head = NULL;
p1 = p2 = (Stu*)malloc(sizeof(Stu));
printf("例:胡歌 34 1/0(当输入0停止输入,1继续输入)\n");
printf("请输入学生信息\n");
scanf_s("%s%f%d", &p1->name, 6, &p1->score, &i);
head = p1;
while (i != 0)
{
p2 = p1;
p1 = (Stu*)malloc(sizeof(Stu));
p2->next = p1;
printf("请输入学生信息");
scanf_s("%s%f%d", &p1->name, 6, &p1->score, &i);
number++;
}
p1->next = NULL;
return head;
}
void print(Stu* head)//输出学生信息
{
Stu* p;
p = head;
while (p != NULL)
{
printf("%s\t%f\n", p->name, p->score);
p = p->next;
}
}
void change(Stu* head, int n) //修改指定位置的结点的信息
{
Stu* p = head;//传入首地址
int i = 1;
while (i < n && p != NULL)//p!=NULL是保证要修改的前一个节点不为空
{
p = p->next;
i++;
}
if (p != NULL)
{
printf("输入要修改的值\n");
scanf_s("%s%f", &p->name, 6, &p->score);
}
else
printf("节点不存在\n");
}
//删除节点信息
Stu* del(Stu* head,int i)//i表示删除第i个节点
{
Stu* p=head;
if (p == NULL)
{
printf("链表为空");
}
Stu *pl=NULL;//pl删除节点的左边节点
int n = 1;
while (n < i&&p!=NULL)
{
pl = p;
p = p->next;
n++;
//pr = p->next;
}
if (n == 1&&p!=NULL)
{
head= p->next;
free(p);
}
else if (n!=1&&p != NULL)
{
p->next = pl->next;
free(p);
}
else
printf("节点不存在");
return head;
}
//节点的插入
Stu *add(Stu* head, int n)//插入到第n个
{
Stu* p = head;
Stu* pl=NULL,*pnew=NULL;
pnew = (Stu*)malloc(sizeof(Stu));
int i = 1;
while (i < n && p != NULL)
{
pl = p;
p = p->next;
i++;
}
if (i==1)
{
printf("请输入要插入的学生信息:\n");
printf("姓名 成绩\n");
scanf_s("%s%f", &pnew->name,6, &pnew->score);
pnew->next = head;
head = pnew;
return head;
}
else if (i != 1)
{
printf("请输入要插入的学生信息:\n");
printf("姓名 成绩\n");
scanf_s("%s%f", &pnew->name, 6, &pnew->score);
pnew->next = pl->next;
pl->next = pnew;
return head;
}
}
int main()
{
int n,i,m;
Stu* pnew,*ph,*p2;
pnew = Creat();
print(pnew);
printf("请输入要修改第几个学生");
scanf_s("%d", &n);
change(pnew, n);
print(pnew);
printf("请输入要删除第几个学生信息");
scanf_s("%d", &i);
ph=del(pnew,i);
print(ph);
printf("请输入要插入第几个学生信息");
scanf_s("%d", &m);
ph=add(ph, m);
print(ph);
return 0;
}
参照xiaoxiaodaweiC语言链表详解附实例