好的,以下是一个使用C语言解决该问题的示例代码:
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
struct ListNode {
int val;
struct ListNode* next;
};
// 创建链表节点
struct ListNode* createNode(int value) {
struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
newNode->val = value;
newNode->next = NULL;
return newNode;
}
// 删除指定值的节点
struct ListNode* deleteNodes(struct ListNode* head, int val) {
while (head != NULL && head->val == val) {
struct ListNode* temp = head;
head = head->next;
free(temp);
}
if (head == NULL) {
return NULL;
}
struct ListNode* current = head;
while (current->next != NULL) {
if (current->next->val == val) {
struct ListNode* temp = current->next;
current->next = current->next->next;
free(temp);
} else {
current = current->next;
}
}
return head;
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* current = head;
printf("LinkedList: ");
while (current != NULL){
printf("%d ", current -> val);
current = current -> next;
}
printf("\n");
}
int main() {
struct ListNode *head, *newNode, *temp;
int n, i, value, delValue;
// 输入链表数据
printf("请输入链表中的元素个数:");
scanf("%d", &n);
if(n <= 0) {
printf("输入错误!\n");
return 0;
}
head = NULL;
for (i = 0; i < n; i++) {
printf("请输入第 %d 个元素的值:", i+1);
scanf("%d", &value);
newNode = createNode(value);
if (head == NULL) {
head = newNode;
temp = head;
} else {
temp -> next = newNode;
temp = temp -> next;
}
}
// 打印原始链表
printList(head);
// 输入要删除的值
printf("请输入要删除的节点值:");
scanf("%d", &delValue);
// 删除指定节点
head = deleteNodes(head, delValue);
// 打印删除后的链表
printList(head);
return 0;
}
请注意,以上代码是一个简单示例,仅供参考。实际应用中,可能需要根据具体需求进行适当修改和扩展。
内容由零声教学AI助手提供,问题来源于学员提问