编写程序删除单链表中所有值为x的节点

编程入门 行业动态 更新时间:2024-10-23 08:31:23

编写程序删除单链表中所有值为x的<a href=https://www.elefans.com/category/jswz/34/1771452.html style=节点"/>

编写程序删除单链表中所有值为x的节点

思路非常简单,就是查找出一个节点p满足值为x,将前驱节点q指向后继节点,然后将此节点删除即可。值得注意的是头节点head为此值时要分开讨论,即直接让头节点的后继节点成为新的头节点。

#include<stdio.h>
#include<math.h>
#include<malloc.h>
typedef struct node {int data;struct node* next;
}node;
node* Delete(node* head,int x) {node* p = head;node* q = NULL;while (p) {if (p->data == x&&p==head) {node* m = head;q = p;head = head->next;p = head;free(m);}else if (p->data == x) {q->next = p->next;node* m = p;p = p->next;free(m);}else {q = p;p = p->next;}}return head;}
int main() {node* a = (node*)malloc(sizeof(node)); a->data = 1; node* b = (node*)malloc(sizeof(node)); b->data = 2; node* c = (node*)malloc(sizeof(node)); c->data = 3;node* d = (node*)malloc(sizeof(node)); d->data = 2;a->next = b; b->next = c; c->next = d; d->next = NULL;node* p = (node*)malloc(sizeof(node));p = Delete(a, 2);while (p) {printf("%d", p->data);p = p->next;}return 0;
}

更多推荐

编写程序删除单链表中所有值为x的节点

本文发布于:2024-02-12 22:24:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1689638.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:节点   值为   链表   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!