加入此时我们有 1,2,3,4,5 五个节点,需要在2节点和3节点之间插入一个节点,新节点是 100。
思路是:
先让 100->next = 2->next;
然后 2->next = 100;
#include <stdio.h>
struct Test
{
int data;
struct Test *next;
};
// 遍历链表并输出
void printLink(struct Test *head)
{
struct Test *p = head;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
}
// 指定节点后方插入
int insertFromBehind(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;
}
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};
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
struct Test t6 = {100, NULL};
printf("use t1 to print three nums\n");
printLink(&t1);
putchar('\n');
ret = insertFromBehind(&t1, 2, &t6);
printLink(&t1);
putchar('\n');
return 0;
}