用C语言删除单链表中最小的元素
时间: 2023-05-31 20:04:57 浏览: 99
以下是用C语言删除单链表中最小的元素的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 单链表结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建单链表
struct ListNode* createList(int arr[], int size) {
struct ListNode *head = NULL, *tail = NULL;
for (int i = 0; i < size; i++) {
struct ListNode *node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = arr[i];
node->next = NULL;
if (tail == NULL) {
head = tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 删除最小元素
struct ListNode* deleteMin(struct ListNode* head) {
if (head == NULL) {
return NULL;
}
struct ListNode *prev = NULL, *minPrev = NULL, *minNode = head;
while (head != NULL) {
if (head->val < minNode->val) {
minPrev = prev;
minNode = head;
}
prev = head;
head = head->next;
}
if (minPrev == NULL) {
head = minNode->next;
} else {
minPrev->next = minNode->next;
}
free(minNode);
return head;
}
// 打印单链表
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
int arr[] = {4, 2, 8, 1, 5};
int size = sizeof(arr) / sizeof(int);
struct ListNode *head = createList(arr, size);
printf("原链表:");
printList(head);
head = deleteMin(head);
printf("删除最小元素后:");
printList(head);
return 0;
}
```
运行结果:
```
原链表:4 2 8 1 5
删除最小元素后:4 2 8 5
```
阅读全文