C语言单链表删除结点:高效代码实现
#include <stdio.h> #include <stdlib.h>
// 定义链表结构体 typedef struct Node { int val; struct Node *next; } Node;
// 创建链表 Node* createList(int n) { Node *head, p, q; head = (Node)malloc(sizeof(Node)); head->next = NULL; q = head; for (int i = 0; i < n; i++) { p = (Node)malloc(sizeof(Node)); scanf("%d", &p->val); p->next = NULL; q->next = p; q = p; } return head; }
// 删除结点 void deleteNode(Node *head, int x, int y) { Node *p, *q; p = head->next; q = head; while (p != NULL) { if (p->val > x && p->val <= y) { q->next = p->next; free(p); p = q->next; } else { q = p; p = p->next; } } }
// 打印链表 void printList(Node *head) { Node *p; p = head->next; while (p != NULL) { printf("%d ", p->val); p = p->next; } printf("\n"); }
// 主函数 int main() { int n, x, y; Node *head; scanf("%d", &n); head = createList(n); scanf("%d%d", &x, &y); deleteNode(head, x, y); printList(head); return 0; }
原文地址: https://www.cveoy.top/t/topic/n35B 著作权归作者所有。请勿转载和采集!