我在之前一篇博客《C语言实现单链表节点的删除(不带头结点)》中具体实现了怎样在一个不带头结点的单链表的删除一个节点,在这一篇博客中我改成了带头结点的单链表。代码演示样例上传至 https://github.com/chenyufeng1991/DeleteLinkedList_HeadNode。删除类型有两种:
(1)删除某个位置pos的节点;
(2)推断x值是否在链表中,若存在则删除该节点;
核心代码例如以下:
//删除某个位置pos的节点
Node *DeletePosNode(Node *pNode,int pos){ int i = 1;
Node *pMove;
Node *pMovePre;
pMovePre = pNode;
pMove = pNode->next;
while (pMove != NULL) {
if (i == pos) { pMovePre->next = pMove->next;
free(pMove);
pMove = NULL;
printf("%s函数运行。在pos=%d位置删除节点成功\n",__FUNCTION__,pos);
return pNode;
}
i++;
pMovePre = pMovePre->next;
pMove = pMove->next;
} printf("%s函数运行,在pos=%d位置删除节点失败\n",__FUNCTION__,pos); return pNode;
} //推断x值是否在链表中,若存在则删除该节点
Node *DeleteValueNode(Node *pNode,int x){ Node *pMovePre;
Node *pMove;
pMovePre = pNode;
pMove = pNode->next;
while (pMove != NULL) {
if (pMove->element == x) {
pMovePre->next = pMove->next;
free(pMove);
pMove = NULL; printf("%s函数运行,删除value=%d节点成功\n",__FUNCTION__,x);
return pNode;
}
pMovePre = pMovePre->next;
pMove = pMove->next;
} printf("%s函数运行,删除value=%d节点失败\n",__FUNCTION__,x); return pNode;
}