Создать список А содержащий вещественные числа. Разбить список А на 2 списка - C (СИ)
Формулировка задачи:
создать список А содержащий вещественные числа. разбить список А на 2
списка -
отрицательных и положительных чисел. в списке,
состоящем из отрицательных чисел найти минимальный элемент
Решение задачи: «Создать список А содержащий вещественные числа. Разбить список А на 2 списка»
textual
Листинг программы
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <assert.h>
typedef struct node_t
{
float value;
struct node_t* next;
} TNode;
typedef struct list_t
{
TNode* head;
TNode* tail;
} TList;
//-----------------------------------------------------------------------------
TList* Push(TList* list, float value)
{
assert(list);
TNode* node = (TNode*) malloc(sizeof(TNode));
node->value = value;
node->next = NULL;
if (list->head && list->tail)
{
list->tail->next = node;
list->tail = node;
}
else
{
list->head = list->tail = node;
}
return list;
}
//-----------------------------------------------------------------------------
void Split(TList* source, TList* positive, TList* negative)
{
assert(source);
assert(positive);
assert(negative);
positive->head = positive->tail = NULL;
negative->head = negative->tail = NULL;
TList* plist = NULL;
TNode* node;
while (source->head)
{
node = source->head;
source->head = source->head->next;
node->next = NULL;
plist = (node->value < 0.0) ? negative : positive;
if (plist->head && plist->tail)
{
plist->tail->next = node;
plist->tail = node;
}
else
{
plist->head = plist->tail = node;
}
}
source->tail = NULL;
}
//-----------------------------------------------------------------------------
TNode* GetMin(TList* list)
{
assert(list);
TNode* min = list->head;
if (list->head)
{
TNode* node = list->head->next;
for (; node; node = node->next)
{
if (node->value < min->value)
{
min = node;
}
}
}
return min;
}
//-----------------------------------------------------------------------------
TList GetRandomList(int count)
{
TList list = {NULL, NULL};
float value;
while (count-- > 0)
{
value = rand() % 100 - 50;
Push(&list, value + (float)(rand() % 100) * 0.01);
}
return list;
}
//-----------------------------------------------------------------------------
void Print(const TList* list)
{
assert(list);
const TNode* node = list->head;
for (; node; node = node->next)
{
printf("%.2f, ", node->value);
}
printf("\b\b \n");
}
//-----------------------------------------------------------------------------
int main()
{
srand(time(NULL));
TList list = GetRandomList(10);
printf("source: ");
Print(&list);
TList positive;
TList negative;
Split(&list, &positive, &negative);
TNode* min;
printf("positive: ");
Print(&positive);
if ((min = GetMin(&positive)) != NULL)
{
printf("min: %.2f\n", min->value);
}
printf("negative: ");
Print(&negative);
if ((min = GetMin(&negative)) != NULL)
{
printf("min: %.2f\n", min->value);
}
return 0;
}