这里有个小技巧,容易错误。传入的是个双重指针 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);
insertListNode(&ghead, 5, 31);
dumpList(ghead);
insertListNode(&ghead, 12, 66);
dumpList(ghead);
return;
}
调试编译
gcc listMain.c list.c -o a.exe -DDEBUG
调试输出
========= Dump List 0xef3010 ===========
22 32 19 53 0 47 29 116 4 6
===================================
List length = 10
node: 0xef3130, data = 6
Can not found num 119
Can not found pos -1 node
find pos 0 node: 0xef3010, data = 22
find pos 5 node: 0xef30b0, data = 47
超过链表长度了!
Can not found pos 12 node
========= Dump List 0xef3150 ===========
70 22 32 19 53 0 47 29 116 4 6
===================================
========= Dump List 0xef3150 ===========
70 22 32 19 53 31 0 47 29 116 4 6
===================================
========= Dump List 0xef3150 ===========
70 22 32 19 53 31 0 47 29 116 4 6 66
===================================