链表任意位置插入删除

链表的插入删除主要是要考虑如果为空表,删除第一个等特殊情况,考虑全面。

具体实现如下

c 复制代码
#include<stdlib.h>
#include<stdio.h>
struct Node {
	int data;
	struct Node* next;
};
struct Node* head;
void print()
{
	struct Node* temp = head;
	printf("list is:");
	while (temp != NULL)//遍历操作
	{
		printf(" %d", temp->data);
		temp = temp->next;

	}
	printf("\n");
}
void Insert(int data, int n)
{
	//先创建该结点
	struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
	temp1->data = data;
	temp1->next = NULL;
	if (n == 1)//如果插在第一个位置
	{
		temp1->next = head;//空表也可以
		head = temp1;
		return;
	}
	//找到要插入位置的前一个
	struct Node* temp2 = head;
	for (int i = 0; i < n - 2; i++)//移动n-2次
	{
		temp2 = temp2->next;
	}
	//把temp2的位置移到第n-1个位置
	temp1->next = temp2->next;
	temp2->next = temp1;
	return;
}
//delete node
//注意如果想删除的结点位于头结点
//删除后要释放空间
void Delete(int n)//删除第n个位置
{
		struct Node* temp1 = head;
		// if the previous node does not exist
		if (n == 1)
		{
			head = head->next;
			free(temp1);
			return;
		}
		// if the previous node  exists
		for (int i = 0; i < n - 2; i++)//移动n-2次
		{
			temp1 = temp1->next;//temp1 points to(n-1)th Node
		}
		struct Node* temp2 = temp1->next;//准备删除的结点
			temp1->next = temp2->next;
		free(temp2);
}
int main()
{
	head = NULL;//初始化空表
	Insert(2, 1);
	Insert(3, 1);
	Insert(4, 3);
	print();//list is: 3 2 4

	Delete(1);
	print();//list is: 2 4
	Delete(2);
	print();//list is: 2 
	return 0;
}
相关推荐
醉颜凉2 分钟前
Elasticsearch 核心数据结构:FST 原理与应用场景全解析
数据结构·elasticsearch·jenkins
love_muming8 分钟前
从 ArrayList 到 LinkedList:Java 集合中数组与链表的深度对比
java·数据结构·链表
05候补工程师25 分钟前
【408数据结构】核心考点:图(Graph)精炼笔记与算法直觉
数据结构·经验分享·笔记·考研·算法·图论
并不喜欢吃鱼25 分钟前
从零开始 C++------ 十四【C++ 数据结构】unordered_map/unordered_set 全解析:从使用到底层模拟实现
开发语言·数据结构·c++
小欣加油33 分钟前
leetcode3633 最早完成陆地和水上游乐设施的时间I
数据结构·c++·算法·leetcode
啦啦啦啦啦zzzz35 分钟前
数据结构:二叉排序树(递归与非递归函数的全部实现)
数据结构·c++·二叉排序树
兰令水1 小时前
leecodecode【二叉树排序+最近公共祖先】【2026.6.2打卡-java版本】
java·数据结构·算法·leetcode
晚风吹红霞1 小时前
C++ list 容器完全指南:从入门到手撕双向链表
c++·链表·list
cpp_25011 小时前
P10109 [GESP202312 六级] 工作沟通
数据结构·c++·算法·题解·洛谷·gesp六级
逻极2 小时前
Redis 从入门到精通:缓存设计与实战
数据结构·redis·缓存·哨兵集群