對鏈表進行增刪改查是最基本的操作。我在上一篇博客《C語言實現鏈表節點的刪除》實現了刪除鏈表中的某個節點。這裡我們要來實現在某個位置插入節點。
核心代碼如下:
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;
}