一、从指定节点后方插入
插入逻辑如图:
插入前: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;
}
二、从指定节点前方插入