用C语言删除单链表中最小值结点
时间: 2024-05-01 13:16:39 浏览: 73
假设单链表的结构体定义如下:
```
typedef struct node {
int data;
struct node* next;
} Node, *LinkList;
```
我们可以先遍历一遍单链表,找到最小值及其前驱结点:
```
Node* prev = NULL; // 最小值的前驱结点
Node* minNode = head; // 最小值结点,默认为头结点
Node* p = head->next;
while (p != NULL) {
if (p->data < minNode->data) {
minNode = p;
prev = head;
} else if (prev != NULL && p->data == minNode->data) {
prev->next = p->next; // 如果存在多个最小值,删除其后面的结点
} else {
prev = p;
}
p = p->next;
}
```
其中,head 是单链表的头结点,即第一个结点的前驱结点。
接下来,我们可以从单链表中删除最小值结点:
```
if (minNode == head) {
head = head->next; // 删除头结点
} else {
prev->next = minNode->next;
}
free(minNode); // 释放空间
```
完整代码如下:
```
void deleteMinNode(LinkList& head) {
Node* prev = NULL;
Node* minNode = head;
Node* p = head->next;
while (p != NULL) {
if (p->data < minNode->data) {
minNode = p;
prev = head;
} else if (prev != NULL && p->data == minNode->data) {
prev->next = p->next;
} else {
prev = p;
}
p = p->next;
}
if (minNode == head) {
head = head->next;
} else {
prev->next = minNode->next;
}
free(minNode);
}
```
阅读全文