数据结构-1.2链表(在任意一个位置插入)

 插入图示过程

 对两种插入情况的分析

链表为空

当链表为空时,只有头指针(这里的插入方法,我们还是选用头插法)

	//在头节点处插入
	if (n == 1) {
		temp->next = head;
		head = temp;
		return;
	}

 链表非空

代码部分如下,我们先给出代码再给出插入过程的解释

	//在其他位置插入,在第n个节点前插入
	struct Node* readlist;
	readlist = head;
	for (int i = 0; i < n-2; i++)
	{
		readlist = readlist->next;//遍历到第n-2个节点
	}
	/*
	这里的插入逻辑是这样子的,你可以认为我们的节点是这样子的[date][next];[date的地址]=temp,[next的地址]=temp.next
	*/
	temp->next = readlist->next;
	readlist->next = temp;

 插入逻辑

 全部代码

/*
我们这里使用的还是头插法
*/
#include<stdio.h>
#include<stdlib.h>
struct Node {
	int date;
	struct Node* next;
};
struct Node* head=NULL;
void Insert(int date, int n) {
	struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
	temp->date = date;
	temp->next = NULL;
	printf("插入的节点信息为:temp->date=%d  ", temp->date);
	//在头节点处插入
	if (n == 1) {
		temp->next = head;
		head = temp;
		return;
	}

	//在其他位置插入,在第n个节点前插入
	struct Node* readlist;
	readlist = head;
	for (int i = 0; i < n-2; i++)
	{
		readlist = readlist->next;//遍历到第n-2个节点
	}
	printf("在节点readlist=%d处插入\n", readlist->date);
	/*
	这里的插入逻辑是这样子的,你可以认为我们的节点是这样子的[date][next];[date的地址]=temp,[next的地址]=temp.next
	*/
	temp->next = readlist->next;
	readlist->next = temp;
}

void Print() {
	struct Node* ReadList = head;
	printf("链表的信息为:");
	while (ReadList != NULL) {
		printf(" %d", ReadList->date);
		ReadList = ReadList->next;
	}
	printf("\n");
}
int main(void) {

	Insert(2,1);
	Print();
	Insert(3,2);
	Print();
	Insert(4, 1);
	Print();
	Insert(5,2);
	Print();
	return 0;
}

 运行结果

 下面这份代码注释比较多,便于初学者去看注释去写代码(最后希望大家给个攒)

#include<stdio.h>
#include<stdlib.h>
struct Node {
	int date;
	struct Node* next;
};
struct Node* head;
void Insert(int date, int n) {
	struct Node* temp=(struct Node*)malloc(sizeof(struct Node));
	temp->date = date;
	temp->next = NULL;

	if (n == 1){
		temp->next = head;
		head = temp;
		return;
	}

	//接下来如果是在其他地方进行插入,首先我们要遍历到插入的那个地方
	/*
	1.我们创建一个临时变量来进行遍历
	2.遍历完之后要进行链表的连接
	*/
	struct Node* tempList;
	tempList = head;
	for (int i = 0; i < n-2; i++)
	{
		//因为我们是从头节点处开始遍历,所以是n-2,我们要遍历到n-1节点处就行了
		tempList = tempList->next;
	}
	temp->next = tempList->next;
	tempList->next = temp;
}
void Print() {
	struct Node* ReadList = head;
	printf("链表的信息为:");
	while (ReadList!=NULL) {
		printf(" %d", ReadList->date);
		ReadList = ReadList->next;
	}
	printf("\n");
}
int main()
{
	head = NULL;
	Insert(2, 1);
	Insert(3, 2);
	Insert(4, 1);
	Insert(5, 2);
	Print();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程者也

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值