本题代码如下(有注释)
void delete_min(linklist* head)
{
while ((*head)->next != NULL)//循环到只剩下头节点
{
lnode* pre = *head;//pre为元素最小结点的前驱结点指针
lnode* p = (*head)->next;//p为工作指针
lnode* q;//指向被删除的结点
while (p->next != NULL)//找到最小的结点
{
if (p->next->data < pre->next->data)
pre = p;//记住当前最小值的前驱
p = p->next;
}
printf("%d ", pre->next->data);//输出最小值结点的数据
q = pre->next;//p指向最小结点
pre->next = q->next;//pre后继指向q的后继
free(q);//释放q结点
}
free(*head);//释放头节点
}
完整测试代码
#include<stdio.h>
#include<stdlib.h>
typedef struct lnode
{
int data;
struct lnode* next;
}lnode,*linklist;
int n = 5;
int a[5] = { 2,1,9,8,7 };
void buildlinklist(linklist* head)//建立单链表
{
*head = (lnode*)malloc(sizeof(lnode));
(*head)->next = NULL;
int i = 0;
lnode* s = *head, * r = *head;
for (i = 0; i < n; i++)
{
s = (lnode*)malloc(sizeof(lnode));
s->data = a[i];
s->next = r->next;
r->next = s;
r = s;
}
r->next = NULL;
}
void delete_min(linklist* head)
{
while ((*head)->next != NULL)//循环到只剩下头节点
{
lnode* pre = *head;//pre为元素最小结点的前驱结点指针
lnode* p = (*head)->next;//p为工作指针
lnode* q;//指向被删除的结点
while (p->next != NULL)//找到最小的结点
{
if (p->next->data < pre->next->data)
pre = p;//记住当前最小值的前驱
p = p->next;
}
printf("%d ", pre->next->data);//输出最小值结点的数据
q = pre->next;//p指向最小结点
pre->next = q->next;//pre后继指向q的后继
free(q);//释放q结点
}
free(*head);//释放头节点
}
int main()
{
linklist head;
buildlinklist(&head);
delete_min(&head);
return 0;
}