给出一个数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 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
- ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
- ¥15 Attention is all you need 的代码运行
- ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
- ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
- ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
- ¥30 关于<main>标签页面跳转的问题
- ¥80 部署运行web自动化项目
- ¥15 腾讯云如何建立同一个项目中物模型之间的联系
- ¥30 VMware 云桌面水印如何添加