C语言基础之链表三

134 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第九天,点击查看活动详情

链表

接上篇,这里我们继续学习单向链表~(注:学习笔记)

对链表的插入操作

对链表的插入是指将一个结点插入到一个已有的链表中。

链表中插入结点,根据插入位置的不同,主要有三种插入方法:

  1. 插入到链表的首部,也就是头结点和首元结点中间;

  2. 插入到链表中间的某个位置;

  3. 插入到链表最末端;

流程图:

image.png

举个栗子

题目要求: 写一个学生成绩管理系统,要求实现添加学生成绩的功能并且能按序输出

思路:这里不仅仅是向链表中插入数据,还要求对链表元素进行排序。

参考代码:

/**
 * 实现插入数据(指针) 
 **/
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>

#define LEN sizeof(struct student)

struct student *create();
struct student *insert(struct student *head, struct student *stu_2);
void print(struct student *head);

int n;//全局变量 用来记录数据的条数 

struct student{
	int num;
	float score;
	struct student *next;
};

int main(){ 
	struct student *stu,*p,stu_2;
	
	stu = create();
	print(stu);
	
	printf("\nPlease input the num to insert:");
	scanf("%d",&stu_2.num);
	printf("Please input the score:");
	scanf("%f",&stu_2.score);
	
	p = insert(stu, &stu_2);
	print(p);
	
}

struct student *create(){
	struct student *head;
	struct student *p1,*p2;

	p1 = p2 = (struct student *)malloc(LEN);
	head = NULL;
	n = 0;
	printf("Please enter the num:");
	scanf("%d",&p1->num);
	printf("Please enter the score:");
	scanf("%f",&p1->score);
	
	while(p1->num){
		n++;
		if(n == 1){
			head = p1;
		} else{
			p2->next = p1;
		}
		p2 = p1;
		
		p1 = (struct student *)malloc(LEN);
		printf("\nPlease enter the num:");
		scanf("%d",&p1->num);
		printf("\nPlease enter the score:");
		scanf("%f",&p1->score);
	}
	p2->next = NULL;
		
	return head;
};

//第一个参数:需要被插入的链表 第二个参数:待插入结构的地址 
struct student *insert(struct student *head, struct student *stu_2){
	struct student *p0,*p1,*p2;
	
	p1 = head;
	p0 = stu_2;
	
	if(NULL == head){
		head = p0;
		p0->next = NULL;
	} 
	else {
		//两种情况推出 
		while((p0->num > p1->num) && (p1->next != NULL)){
			p2 = p1;
			p1 = p1->next;
		}
		if(p0->num <= p1->num){
			if(p1 == head){ //插到表头之前 
				head = p0;
				p0->next = p1;
			} else{ //插到表中间 
				p2->next = p0;
				p0->next = p1;
			}
		} else{ //插到表尾之后 
			p1->next = p0;
			p0->next = NULL;
		}
	}
	n = n+1;
	return head;
};

void print(struct student *head){
	struct student *p;
	p = head;
	if(head){
		do{
			printf("学号为 %d 的学生成绩为:%f\n",p->num,p->score);
			p = p->next;
		}while(p);
	}
}

声明

小编是跟着b站上的小甲鱼视频学习的,希望每天都能进步一点点!!

链接附上:C语言学习之小甲鱼视频链接