一、从指定节点后方插入
插入逻辑如图:
插入前:A指向B,B指向C
插入后:B为插入点,当要插入D时就要让B指向D,D再指向C(插入前B的指向)
#include <stdio.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
while(1){
if(head != NULL){
printf("%d ",head->data);
head = head->next;
}else{
printf("\n");
break;
}
}
}
int getLinkNum(struct Test *head)
{
int cnt =0;
while(head !=NULL){
cnt ++;
head = head->next;
}
return cnt;
}
int searchLink(struct Test *head,int data)
{
while(head != NULL){
if(head->data == data){
return 1;
}
head = head->next;
}
return 0;
}
int insertBhind(struct Test *head,int data,struct Test *new)
{
struct Test *p = head;
while(p !=NULL){
if(p->data == data){
new->next = p->next; //新插入的链表指向插入点的链表
p->next = new; //插入点指向新插入的链表
return 1;
}
p = p->next; //循环结束,p指向后面的链表
}
return 0;
}
int main(){
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
printLink(&t1);
int ret =getLinkNum(&t1);
printf("total num = %d\n",ret);
ret = searchLink(&t1,1);
if(ret = 0){
printf("没有data = 1\n");
}else{
printf("有data = 1\n");
}
struct Test new={100,NULL}; //定义“new”链表
insertBhind(&t1,3,&new); //在数据等于3的位置插入“new”链表
printLink(&t1);
return 0;
}
二、从指定节点前方插入
插入逻辑如图:
插入前:A指向B,B指向C
插入后:B为插入点,当要插入D时就要让A指向D,D再指向B(插入前A的指向)
①当插入点为链表头:
那么就要找到链表头,让新链表指向当前的链表头,而新链表头顺位称为新的链表头,使其插入最前端。
struct Test* insertAhead(struct Test *head,int data,struct Test *new)
{
if(head->data == data){
new->next=head;
return new;
}
}
struct Test *head = &t1;
printLink(&t1);
struct Test new2={200,NULL};
head = insertAhead(head,1,&new2);
puts("after insert ahead:\n");
printLink(head);
输出结果:
1 2 3 4
after insert ahead:
200 1 2 3 4
②任意位置插入新链表
目标插入位置是插入链表的目标指向,而目标插入位置的前一位就指向了新插入的链表
#include <stdio.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
while(1){
if(head != NULL){
printf("%d ",head->data);
head = head->next;
}else{
printf("\n");
break;
}
}
}
int getLinkNum(struct Test *head)
{
int cnt =0;
while(head !=NULL){
cnt ++;
head = head->next;
}
return cnt;
}
int searchLink(struct Test *head,int data)
{
while(head != NULL){
if(head->data == data){
return 1;
}
head = head->next;
}
return 0;
}
struct Test* insertAhead(struct Test *head,int data,struct Test *new)
{
struct Test *p = head; //定义一个新的指针变量
if(head->data == data){
new->next=p;
return new;
}
while(p->next != NULL){ //寻找目标数据进行插入
if(p->next->data == data){
new->next = p->next;
p->next = new;
return head; //返回初始链表头
}
p = p->next;
}
printf("no this data\n");
}
int main(){
struct Test t1 = {1,NULL};
struct Test t2 = {2,NULL};
struct Test t3 = {3,NULL};
struct Test t4 = {4,NULL};
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
struct Test *head = &t1;
printLink(&t1);
struct Test new1={200,NULL};
head = insertAhead(head,1,&new1);
puts("after insert head:\n");
printLink(head);
struct Test new2={400,NULL}; //在3前面插入400
head = insertAhead(head,3,&new2);
puts("after insert ahead:\n");
printLink(head);
return 0;
}