给出一个数x,从双向链表中删除所有元素x的结点
4条回答 默认 最新
- 技术专家团-小桥流水 2021-12-28 08:26关注
大体思路是:
(1)遍历链表
(2)判断当前节点的data是否等于x
(3)如果等于x,ppre记录上一个节点,nnext记录下一个节点,
ppre->next = nnext; nnext->pre = ppre;
删除当前节点的内存
继续判断下一个节点。
(4)如果不等于,继续遍历下一个节点代码如下:
#include <stdio.h> #include <stdlib.h> struct stnode { int data; struct stnode* pre; struct stnode* next; }; //创建双向链表 struct stnode* create() { int i; struct stnode* head,*p,*t; head = (struct stnode*)malloc(sizeof(struct stnode)); head->pre = NULL; head->next = NULL; t = head; //创建5个节点 for (i=0;i<5;i++) { p = (struct stnode*)malloc(sizeof(struct stnode)); p->pre = NULL; p->next = NULL; printf("请输入1个整数:"); scanf("%d",&p->data); t->next = p; p->pre = t; t = p; } return head; } //删除值为x的节点 struct stnode* del(struct stnode* head,int x) { struct stnode *p,*ppre,*nnext; p = head->next; while (p) { if(p->data == x) { ppre = p->pre; nnext = p->next; ppre->next = nnext; if(nnext) nnext->pre = ppre; free(p); p = nnext; }else p = p->next; } return head; } //xians void show(struct stnode* head) { struct stnode* p = head->next; while(p) { printf("%d ",p->data); p = p->next; } } //free void Release(struct stnode* head) { struct stnode* p; while(head) { p = head->next; free(head); head = p; } } int main() { int x; struct stnode* head = create(); show(head); printf("请输入需要删除的值:"); scanf("%d",&x); head = del(head,x); //显示 show(head); //释放空间 Release(head); return 0; }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报 编辑记录
悬赏问题
- ¥15 微信会员卡等级和折扣规则
- ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
- ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
- ¥15 gdf格式的脑电数据如何处理matlab
- ¥20 重新写的代码替换了之后运行hbuliderx就这样了
- ¥100 监控抖音用户作品更新可以微信公众号提醒
- ¥15 UE5 如何可以不渲染HDRIBackdrop背景
- ¥70 2048小游戏毕设项目
- ¥20 mysql架构,按照姓名分表
- ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分