C语言建立长度为n的单链表,n>0,删除单链表中等于给定值的元素。数据类型指定为整型。 输入格式: 第一行为链表长度n; 第二行为链表中的n个数据元素的值; 第三行为需要删除的元素值。 输出格式: 输出为删除后的链表中的所有数据元素的值。 输入样例: 4 45 12 34 8 34 输出样例: 45 12 8
时间: 2023-12-10 13:42:07 浏览: 35
以下是 C 语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 创建链表
struct ListNode* createList(int* nums, int numsSize) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < numsSize; i++) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = nums[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 删除链表中等于给定值的元素
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->val = 0;
dummy->next = head;
struct ListNode* pre = dummy;
struct ListNode* cur = head;
while (cur != NULL) {
if (cur->val == val) {
pre->next = cur->next;
free(cur);
cur = pre->next;
} else {
pre = cur;
cur = cur->next;
}
}
return dummy->next;
}
// 打印链表
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
int n;
scanf("%d", &n);
int* nums = (int*)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
int val;
scanf("%d", &val);
struct ListNode* head = createList(nums, n);
head = removeElements(head, val);
printList(head);
return 0;
}
```