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;
}


posted @ 2017-08-11 12:20  wzjhoutai  阅读(888)  评论(0编辑  收藏  举报