单链表中查找最小的

用c语言在单链表中查找出最小的数据,这个单链表数据域为纯整数数字
2026年09月17日 00:19
有3个网友回答
网友(1):

从头开始检索,设定第一个为最小值,每个数据与最小值比较,有更小的用更小的代替未最小值,循环都最后一个值。

网友(2):

#include "stdio.h"

/* 链表结点结构 */
typedef struct LNode{
int data;
struct LNode *next;
}LNode;

/* 将值为data的结点插入到head链表的最后 */
void Insert(LNode *head, int data)
{
LNode *pre = head->next;
LNode *temp;
temp = (LNode*)malloc(sizeof(LNode));
temp->data = data;
temp->next = NULL;

if(pre == NULL)
{
head->next = temp;
return;
}

for(; pre->next!=NULL; pre=pre->next);

pre->next = temp;
}

/* 输出head链表的所有结点的值 */
void list(LNode *head)
{
LNode *curr;
for(curr=head->next; curr!=NULL; curr=curr->next)
{
printf("%d\t", curr->data);
}
}

/* 返回head链表结点的最小值 */
int findMinValue(LNode *head)
{
int min;
LNode *curr;

curr = head->next;

if(curr == NULL)
{
return -32766;
}
min = curr->data;
for(; curr!=NULL; curr=curr->next)
{
if(curr->data < min)
min = curr->data;
}

return min;
}

void main()
{
int min;
LNode *head;
head = (LNode*)malloc(sizeof(LNode));
head->next = NULL;
Insert(head, 49);
Insert(head, 38);
Insert(head, 65);
Insert(head, 97);
Insert(head, 76);

printf("all nodes : ");
list(head);

min = findMinValue(head);
printf("\nmin value : %d\n", min);
}

网友(3):

/*单链表的数据结构*/
typedef struct node{
int data;
struct node *next;
} *list,node;

/*计算最小值的函数*/
int min(list head)
{
int Min=head->data;
node *now=head->next;
while (now!=NULL)
{
if (Min>now->data) Min=now->data;
now=now->next;
}
return Min;
}