这里有个小技巧,容易错误。传入的是个双重指针 st_dataNode** phead,因为删除在首节点的位置时候,链表头的位置会发生改变,指向新的节点,所以需要传入双重指针,以便接收修改的新的链表头的位置
代码实现
st_dataNode * removeListNode(st_dataNode** phead, int pos){
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;
if(0 == pos) { /*首节点*/
nw = head;
p = head->next;
nw->next = NULL;
*phead = p;
} else { /* 其他节点 */
/* 注意,要找前面一个节点,单链表才能前后都链接上*/
p = findListPos(head, pos - 1);
nw = p->next;
q = nw->next;
p->next = q;
nw->next = NULL;
}
return nw;
}
void testRemoveNode(void){
st_dataNode * nw = NULL;
nw = removeListNode(&ghead, 12);
if(NULL != nw)
printf("Removed node %p: data %d\n", nw, nw->data);
dumpList(ghead);
nw = removeListNode(&ghead, 5);
if(NULL != nw)
printf("Removed node %p: data %d\n", nw, nw->data);
dumpList(ghead);
nw = removeListNode(&ghead, 0);
if(NULL != nw)
printf("Removed node %p: data %d\n", nw, nw->data);
dumpList(ghead);
return;
}
调试编译
gcc listMain.c list.c -o a.exe -DDEBUG
调试输出
========= Dump List 0x193b010 ===========
22 32 19 53 0 47 29 116 4 6
===================================
List length = 10
node: 0x193b130, data = 6
Can not found num 119
Can not found pos -1 node
find pos 0 node: 0x193b010, data = 22
find pos 5 node: 0x193b0b0, data = 47
超过链表长度了!
Can not found pos 12 node
========= Dump List 0x193b150 ===========
70 22 32 19 53 0 47 29 116 4 6
===================================
========= Dump List 0x193b150 ===========
70 22 32 19 53 31 0 47 29 116 4 6
===================================
========= Dump List 0x193b150 ===========
70 22 32 19 53 31 0 47 29 116 4 6 66
===================================
Removed node 0x193b190: data 66
========= Dump List 0x193b150 ===========
70 22 32 19 53 31 0 47 29 116 4 6
===================================
Removed node 0x193b170: data 31
========= Dump List 0x193b150 ===========
70 22 32 19 53 0 47 29 116 4 6
===================================
Removed node 0x193b150: data 70
========= Dump List 0x193b010 ===========
22 32 19 53 0 47 29 116 4 6
===================================