链表的插入

本文详细介绍了一个简单的链表实现过程,包括链表的创建、查找指定元素的位置以及在特定位置插入新元素的方法。通过具体的C++代码示例,读者可以更好地理解链表的基本操作及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstdio>


using namespace std;
struct node{
    int data;
    node* next;
};
node* create(int *a){
    node* p,*pre,*head;
    head =new node;
    head->next=NULL;
    pre=head;
    for(int i=0;i<5;i++){
        p = new node;
        p->data=a[i];
        p->next=NULL;
        pre->next=p;
        pre=p;
    }
    return head;
}
int findpos(node* l,int x){
    int ans=-1;
    int cnt=0;
    while(l){
        if(l->data==x) {
            ans=cnt;
            break;
        }
        l=l->next;
        cnt++;
    }
    return ans;
}
void insertn(node* l,int pos ,int num){
    //find pre node;
    node* p=l;
    for(int i=0;i<pos-1;i++){
        p=p->next;
    }
    node* q=new node;
    q->data=num;
    q->next=p->next;
    p->next=q;
}
int main()
{
    int Array[5]={5,3,6,1,2};
    node* L = create(Array);
    L=L->next;


//  返会节点的个数;
//    int cnt=0;
//    while(L){
//        L=L->next;
//        cnt++;
//    }
//    printf("%d",cnt);'
    int pos = findpos(L,2);
//    printf("%d",pos);
    int num=100;
    insertn(L,2,num);
    while(L){
       printf("%d ",L->data);
        L=L->next;
    }
    return 0;

}


//链表的插入分为2步,

1.找到插入的位置的前一个;

2.把数据保存起来,尾接和头接;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值