#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data; // 数据域
struct Node *next; // 指针域,指向下一个节点
} Node;
// 创建链表
Node *createList(int num) {
Node *head, *p, *q;
head = (Node *)malloc(sizeof(Node));
head->next = NULL;
q = head;
for (int i = 0; i < num; i++) {
p = (Node *)malloc(sizeof(Node));
scanf("%d", &(p->data));
p->next = NULL;
q->next = p;
q = p;
}
return head;
}
// 打印链表
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
// 删除链表中所有值为m的节点
void deleteNode(Node *head, int m) {
Node *p = head->next;
Node *q = head;
while (p != NULL) {
if (p->data == m) {
q->next = p->next;
free(p);
p = q->next;
} else {
q = p;
p = p->next;
}
}
}
int main() {
int num, m;
printf("请输入正整数个数:");
scanf("%d", &num);
printf("请依次输入这%d个正整数:", num);
Node *head = createList(num);
printf("创建的链表为:");
printList(head);
printf("请输入要删除的整数m:");
scanf("%d", &m);
deleteNode(head, m);
printf("删除值为%d的结点后,链表为:", m);
printList(head);
return 0;
}
输入若干个正整数(输入-1为结束标志)建立一个单向链表,再输入一个整数m,删除链表中值为m的所有结点。
最新推荐文章于 2023-05-11 09:04:28 发布