这里有个小技巧,容易错误。传入的是个双重指针 st_dataNode** phead,因为插入在首节点的位置时候,链表头的位置会发生改变,指向新的节点,所以需要传入双重指针,以便接收修改的新的链表头的位置
代码实现
/*
* 传入head是二重指针,是因为插入头结点的时候,会改变head的指向到新的节点
*/
st_dataNode * insertListNode(st_dataNode** phead, int pos, int data){
if(NULL == phead || pos < 0){
printf("%s: param error\n",__func__);
return NULL;
}
st_dataNode * head = *phead;
st_dataNode * p = NULL;
st_dataNode * q = NULL;
st_dataNode * nw = NULL;
nw = (st_dataNode *) malloc(sizeof(st_dataNode));
if(NULL == nw){
printf("%s: memory alloc failed\n", __func__);
return NULL;
}
nw->data = data;
if(0 == pos){ // 首节点
p = head;
nw->next = p;
*phead = nw; /*插入后更新首节点的值*/
} else { // 中间节点
/* 注意,要找前面一个节点,单链表才能前后都链接上*/
p = findListPos(head, pos - 1);
q = p->next;
p->next = nw;
nw->next = q;
}
return nw;
}
void testInsertNode(void){
st_dataNode * nw = NULL;
nw = insertListNode(&ghead, 0, 70);
dumpList(ghead);
ins

最低0.47元/天 解锁文章
1772

被折叠的 条评论
为什么被折叠?



