linux——链表(从指定节点后方插入新节点)

从指定节点后方插入新节点
找到节点位置
new->next=p->next; 将新节点指向原先p节点指向的位置
p->next=new; 前一个节点的next指向新节点

#include<stdio.h>
struct Test
{
    int data;
    struct Test *next;
};

int insertfrombehind(struct Test *head,int data,struct Test *new)
{
    while(head!=NULL){
        if(head->data==data){//same as data
            new->next=head->next;//insert *new
            head->next=new;
            return 1;
        }
        head=head->next;
    }
    return 0;
}

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

int main()
{
    int i;
    int array[]={1,2,3,4,5,6,7,8,9,10};
    for(i=0;i<sizeof(array)/sizeof(array[0]);i++){
        printf("%d ",array[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 t6={6,NULL};//tianjia
    struct Test new={100,NULL};

    t1.next=&t2;//t1=lianbiaotou
    t2.next=&t3;
    t3.next=&t4;
    t4.next=&t5;
   // t5.next=&t6;

    printf("use t1 to print three num\n");
    printlink(&t1);
    puts("after insert behind\n");
    insertfrombehind(&t1,5,&new);
    printlink(&t1);

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值