已知一个单向链表的头,请写出删除其某一个结点的算法,要求,先找到此 结点,然后删除。用C语言实现
时间: 2023-10-04 11:09:31 浏览: 168
以下是单向链表删除某一结点的C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结点结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 删除指定结点
void deleteNode(struct ListNode* head, int val) {
struct ListNode* prev = head;
struct ListNode* curr = head->next;
while(curr != NULL) {
if(curr->val == val) {
prev->next = curr->next;
free(curr);
return;
}
prev = curr;
curr = curr->next;
}
}
int main() {
// 创建链表
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->val = 0;
head->next = NULL;
struct ListNode* node1 = (struct ListNode*)malloc(sizeof(struct ListNode));
node1->val = 1;
node1->next = NULL;
struct ListNode* node2 = (struct ListNode*)malloc(sizeof(struct ListNode));
node2->val = 2;
node2->next = NULL;
head->next = node1;
node1->next = node2;
// 删除结点2
deleteNode(head, 2);
// 打印链表
struct ListNode* curr = head->next;
while(curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
return 0;
}
```
注:此实现中假设链表中不会有重复元素。如果链表中有重复元素,需要改写删除结点的判断条件。
阅读全文