链表从指定节点后方插入新节点

在指定数据后面插入节点的案例:在Test结构体(这个结构体的data为2)后面插入一个Test结构体(data=6)

#include<stdio.h>

struct Test
{
  int data;
  struct Test * next;
};

printfLink(struct Test * head)
{
   while(head!=NULL)
   {
      printf("%d\n",head->data);
      head=head->next;
   }
   putchar('\n');
}

void InsertNode(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;
        }
        p=p->next;
    }
}

int main()
{
   struct Test t1={1,NULL};
   struct Test t2={2,NULL};
   struct Test t3={3,NULL};
   t1.next=&t2;
   t2.next=&t3;
   printf("before insert:\n");
   printfLink(&t1);
   struct Test new={6,NULL};
   InsertNode(&t1,2,&new);
   printf("after insert:\n");
   printfLink(&t1);
}

 输出结果:

before insert:
1
2
3

after insert:
1
2
6
3


 

posted @ 2022-12-05 22:30  WellMandala  阅读(66)  评论(0编辑  收藏  举报