用C语言实现单链表删除指定节点的元素
时间: 2024-05-30 08:16:21 浏览: 84
#include <stdio.h>
#include <stdlib.h>
// 定义单链表节点结构体
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
// 创建单链表
ListNode* createList(int arr[], int n) {
ListNode *head = NULL, *p = NULL;
for (int i = 0; i < n; i++) {
ListNode *node = (ListNode*)malloc(sizeof(ListNode));
node->val = arr[i];
node->next = NULL;
if (!head) {
head = node;
p = head;
} else {
p->next = node;
p = p->next;
}
}
return head;
}
// 删除指定节点
ListNode* deleteNode(ListNode* head, int val) {
ListNode *p = head, *pre = NULL;
while (p) {
if (p->val == val) {
if (pre) {
pre->next = p->next;
} else {
head = p->next;
}
free(p);
break;
}
pre = p;
p = p->next;
}
return head;
}
// 打印单链表
void printList(ListNode *head) {
ListNode *p = head;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
ListNode *head = createList(arr, n);
printf("原始链表:");
printList(head);
head = deleteNode(head, 3);
printf("删除节点3后:");
printList(head);
return 0;
}
阅读全文