链表任意位置插入删除

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

具体实现如下

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;
}
相关推荐
ShineWinsu13 分钟前
对于数据结构:堆的超详细保姆级解析——下(堆排序以及TOP-K问题)
c语言·数据结构·c++·算法·面试·二叉树·
少许极端2 小时前
算法奇妙屋(十)-队列+宽搜(BFS)
java·数据结构·算法·bfs·宽度优先·队列
异步的告白3 小时前
C语言-数据结构-1-动态数组
c语言·数据结构·c++
Miraitowa_cheems5 小时前
LeetCode算法日记 - Day 98: 分割回文串 II
数据结构·算法·leetcode·深度优先·动态规划
立志成为大牛的小牛5 小时前
数据结构——三十九、顺序查找(王道408)
数据结构·学习·程序人生·考研·算法
2301_807997386 小时前
代码随想录-day30
数据结构·c++·算法·leetcode
ゞ 正在缓冲99%…6 小时前
leetcode1771.由子序列构造的最长回文串长度
数据结构·算法·leetcode
snakecy8 小时前
二叉树、动态规划与链表学习
学习·链表·动态规划
Mr.H01278 小时前
快速排序的常见构思
数据结构·算法
懒羊羊不懒@9 小时前
JavaSe—Stream流☆
java·开发语言·数据结构