1.第一种情况:
在头节点插入时,head和p都指在1,new ->next = head;return new;返回new节点地址,由打印函数打印即可成功插入
2.第二种情况:
2.1当我们要在第2个节点插入时,p和head都是指向1节点的,我们得用while循环判断p->next !=NULL;(是否等于空)
然后用if()函数把判断p->next->data 与我们要在所在的节点的data值相比是否相等 ;否则:printf("no this data %d",data);返回head(头节点);
如果相等则:new->next = p->next ; p ->next = new; 插入成功,返回head,
3.第三种情况:
当我们想要改变的节点都不在1,2节点,而头节点又在1节点位置时;我们可以在以上两种情况的基础上用
p = p ->next;
从头遍历节点!
为什么返回head?
because head list never change!!!
#include<stdio.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
struct Test *point;
point = head;
printf("use Link to print num:\n");
while(point !=NULL){
printf("%d ",point->data);
point = point->next;
}
putchar('\n');
}
int getLinkTotalnums(struct Test *head)
{
int count = 0;
while(head != NULL){
count++;
head = head ->next;
}
return count;
}
struct Test *insertFromFor(struct Test *head,int data,struct Test *new)
{
struct Test *point;
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 is ok!\n");
return head;
}
point = point ->next;
}
printf("no have this data %d\n",data);
return head;
}
struct Test *insertFromHead(struct Test *head,int data,struct Test *new2)
{
struct Test *p;
p = head;
if(p->data == data){
new2->next = head;
return new2;
}
}
int main()
{
int i;
int arr[] = {1,2,3,4,5,6,7,8,9,10};
struct Test *head;
for(i =0 ;i<sizeof(arr)/sizeof(arr[0]);i++){
printf("%d ",arr[i]);
}
putchar('\n');
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 new2 = {666,NULL};
struct Test new3 = {999,NULL};
head = &t1;
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
printLink(head);
head = insertFromHead(head,1,&new2);
printLink(head);
head = insertFromFor(head,4,&new3);
printLink(head);
return 0;
}
实验效果图: