从指定节点后方插入新节点
假设我们已有五个节点,我们要把一个新节点new插入到3后边。
需要三个步骤:
- 找到 3 这个节点。
- 把新节点指向3这个节点的下一个节点(3->next = new->next)。
- 把3指向新节点。(3->next = new)
#include <stdio.h>
//定义结构体
struct Test
{
int data;
struct Test *next;//链表有一个指向自己的指针
};
//输出链表数据
void printLink(struct Test *head)
{
struct Test *piont = head;
while(piont != NULL){
printf("%d ",piont->data);
piont = piont->next;
}
putchar('\n');
}
int insertFromBehind(struct Test *head,int data,struct Test *new)
{
struct Test *point = head;
while(point != NULL){
if(point->data == data){
new->next = point->next;
point->next = new;
return 1;
}
//跳到下一节点
point = point->next;
}
return 0;
}
int main()
{
//定义结构体变量
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};
struct Test t5 = {5,NULL};
struct Test new = {100,NULL};
//指向对应节点地址形成链表
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
//插入前输出
printLink(&t1);
int ret = insertFromBehind(&t1,3,&new);
//插入反馈
if(ret){
printf("insert Succeed\n");
}else{
printf("insert Fail\n");
}
//插入后输出
printf("after inerst \n");
printLink(&t1);
return 0;
}
执行结果:
从指定节点前方插入新节点
从指定节点前插入新节点要考虑到两种情况:
一、从第一个节点(头结点)前插入
假设我们已有五个节点,我们要把一个新节点new插入到头节点前。只需把新节点指向原来的头结点并将其变为新的头结点即可。
二、不在头节点前插入
假设我们已有五个节点,我们要把一个新节点new插入到3前边。
- 如果不是头结点,我们首先判断当前所指向的节点是不是尾结点。
- 假设我们要插入到 3 这个节点前, 在函数中piont刚好指向到了 2 这个节点,我们就判断 2 这个节点的下一个节点的 data 是否与我们所要插入的节点数据相同(point->next->data == data)。如果相同则把该节点指向 3 节点(new->next = point->next)。
- 把2指向新节点。(2->next = new)
#include <stdio.h>
//定义结构体
struct Test
{
int data;
struct Test *next;//链表有一个指向自己的指针
};
//输出链表数据
void printLink(struct Test *head)
{
struct Test *piont = head;
while(piont != NULL){
printf("%d ",piont->data);
piont = piont->next;
}
putchar('\n');
}
struct Test *insertFromFront(struct Test *head,int data,struct Test *new)
{
struct Test *point = head;
if(point->data == data){
new->next = head;
return new;
}
while(point->next != NULL){
if(point->next->data == data){
new->next = point->next;
point->next = new;
printf("Insert succeed!\n");
return head;
}
//跳到下一节点
point = point->next;
}
printf("Insert faulat!\n");
return head;
}
int main()
{
//定义结构体变量
struct Test *head = NULL;
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};
struct Test t5 = {5,NULL};
struct Test new = {100,NULL};
//指向对应节点地址形成链表
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
head = &t1;
//输出
printLink(head);
struct Test new2 = {222,NULL};
head = insertFromFront(head, 3, &new2);
printLink(head);
return 0;
}
执行结果:
非头结点:
头结点: