链表删除分为头删除和中间删除(包含尾删除)。
同时注意单向链表原则:先连后断。
具体方法如下:
#include<stdio.h>
#include<stdlib.h>typedef struct node
{int s;struct node* pnext;
}list;list* addnode(list** pphead, list** ppend, int n)
{list* ptemp = malloc(sizeof(list));ptemp->s = n;ptemp->pnext = NULL;if (NULL == *pphead){*pphead = ptemp;*ppend = ptemp;}else{(*ppend)->pnext = ptemp;*ppend = ptemp;}
}void deletenode(list** pphead, list** ppend, int val)
{list* pdel = NULL;//头删除//删除标记指向头节点//头指针指向头结点的下一个//释放if ((*pphead)->s == val){pdel = *pphead;*pphead = (*pphead)->pnext;free(pdel);pdel = NULL;return;}list* pmark = *pphead;//中间删除//遍历链表//找到删除节点的前一个结点//删除标记指向遍历标记的下一个//遍历标记的下一个指向遍历标记的下一个的下一个//释放while (pmark->pnext != NULL){if (pmark->pnext->s == val){pdel = pmark->pnext;pmark->pnext = pmark->pnext->pnext;free(pdel);pdel = NULL;if (pmark->pnext == NULL)//判断是否是尾删除{*ppend = pmark;}return;}pmark = pmark->pnext;}}int main()
{list* phead = NULL;list* pend = NULL;//添加几个节点addnode(&phead, &pend, 1);addnode(&phead, &pend, 2);addnode(&phead, &pend, 3);addnode(&phead, &pend, 4);//删除deletenode(&phead, &pend, 4);//遍历链表,检查是否成功删除while (phead != NULL){printf("%d\n", phead->s);phead = phead->pnext;}return 0;
}