插入图示过程
对两种插入情况的分析
链表为空
当链表为空时,只有头指针(这里的插入方法,我们还是选用头插法)
//在头节点处插入
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();
}