C语言实现单链表(不带头结点)节点的插入

       对单链表进行增删改查是最主要的操作。我在上一篇博客《C语言实现链表节点的删除》实现了删除单链表中的某个节点。

这里我们要来实如今某个位置插入节点。演示样例代码上传至https://github.com/chenyufeng1991/InsertList  。

核心代码例如以下:

Node *InsertToPosition(Node *pNode,int pos,int x){

    if (pos < 0 || pos > sizeList(pNode) ) {
        printf("%s函数运行,pos=%d非法,插入数据失败\n",__FUNCTION__,pos);
        return pNode;
    }

    Node *pMove;
    Node *pInsert;
    pInsert = (Node *)malloc(sizeof(Node));
    memset(pInsert, 0, sizeof(Node));
    pInsert->next = NULL;
    pInsert->element = x;

    pMove = pNode;
    int i = 1;

    //这里单独考虑pos=0的情况
    if (pos == 0) {
        pInsert->next = pNode;
        pNode = pInsert;
        printf("%s函数运行,在pos=%d插入x=%d成功\n",__FUNCTION__,pos,x);
        return pNode;
    }

    while (pMove != NULL) {
        if (i == pos) {
            pInsert->next = pMove->next;
            pMove->next = pInsert;
            printf("%s函数运行。在pos=%d插入x=%d成功\n",__FUNCTION__,pos,x);
            break;
        }
        i++;
        pMove = pMove->next;
    }

    return pNode;
}


转载于:https://www.cnblogs.com/wzjhoutai/p/7345314.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值