赞
踩
思路非常简单,就是查找出一个节点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;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。