核心思想
- 当目标节点为第一个节点时

- 当目标节点为非首节点时

核心代码
- 当目标节点为第一个节点时
if(p->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;
}
return head;
头插法
struct Test* insertFront(struct Test* phead,int data,struct Test* new)
{
struct Test* p;
p=phead;
if(p->data==data)
{
new->next=p;
return new;
}
while(p->next!=NULL)
{
if(p->next->data==data)
{
new->next=p->next;
p->next=new;
return phead;
}
p=p->next;
}
return phead;
}
示例
将 99 插入到 1 前,88 插入到 8 前。
#include <stdio.h>
struct Test
{
int data;
struct Test* next;
};
void printLink(struct Test* phead)
{
struct Test* point=phead;
while(point!=NULL)
{
printf("%d ",point->data);
point=point->next;
}
putchar('\n');
/*
while(1)
{
if(phead!=NULL)
{
printf("%d ",phead->data);
phead=phead->next;
}
else
{
putchar('\n');
break;
}
}
*/
}
int totalNodeNum(struct Test* phead)
{
struct Test* p;
p=phead;
int cnt=0;
while(p!=NULL)
{
cnt++;
p=p->next;
}
return cnt;
}
int searchNode(struct Test* phead,int data)
{
struct Test* p;
p=phead;
while(p!=NULL)
{
if(p->data==data)
{
return 1;
}
p=p->next;
}
return 0;
}
void insertBehind(struct Test* phead,int data,struct Test* new)
{
struct Test* p;
p=phead;
while(p!=NULL)
{
if(p->data==data)
{
new->next=p->next;
p->next=new;
}
p=p->next;
}
}
struct Test* insertFront(struct Test* phead,int data,struct Test* new)
{
struct Test* p;
p=phead;
if(p->data==data)
{
new->next=p;
return new;
}
while(p->next!=NULL)
{
if(p->next->data==data)
{
new->next=p->next;
p->next=new;
return phead;
}
p=p->next;
}
return phead;
}
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 t6={6,NULL};
struct Test t7={7,NULL};
struct Test t8={8,NULL};
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
t4.next=&t5;
t5.next=&t6;
t6.next=&t7;
t7.next=&t8;
printLink(&t1);
int total=0;
total=totalNodeNum(&t1);
printf("total num=%d\n",total);
struct Test t100={100,NULL};
insertBehind(&t1,6,&t100);
printf("after inserting behind:\n");
printLink(&t1);
struct Test* head=&t1;
struct Test t99={99,NULL};
head=insertFront(head,1,&t99);
printf("after inserting front:\n");
printLink(head);
struct Test t88={88,NULL};
head=insertFront(head,8,&t88);
printf("after inserting front:\n");
printLink(head);
return 0;
}
运行结果:


本文介绍了链表操作中的头插法,包括核心思想和代码实现。头插法允许在链表中指定位置插入新节点,示例展示了如何将99插入到1前以及88插入到8前的链表中。代码详细解释了不同情况下的插入逻辑,并提供了完整的插入函数和主函数示例。
2313

被折叠的 条评论
为什么被折叠?



