对单链表进行增删改查是最基本的操作。我在上一篇博客《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 =