C/C++

Создать двусвязный список

Создать двусвязный список с числами в диапазоне от –50
до +50. Найти минимальный элемент и сделать его
вот мой код но мне сказали что это односвязный список

 #include  
#include

#include

int main()

{
struct TNode
{
int value;
struct TNode* next;
} *first = NULL, * second = NULL, * node = NULL;
size_t count;
setlocale(LC_ALL, "Rus");
printf("введите число элементов: ");
scanf_s("%u", &count);

while (count--)
{
node = (struct TNode*)malloc(sizeof(struct TNode));
node->value = rand() % 100 - 50;

if (node->value < 0)
{
node->next = second;
second = node;
}
else
{
node->next = first;
first = node;
}

printf("%d ", node->value);
}
printf("\n\n");


return 0;
}
помогите плиз с реализацией
В двусвязных списках, узел помимо указателя на след. элемент, хранит ещё и указатель на предыдущий элемент.

Т.е. в вашу структуру TNode нужно добавить поле prev:
 struct TNode  
{
int value;
struct TNode* next;
struct TNode* prev;
} // ...

Полная реализация:
 #include  
#include
#include

struct node
{
int value;
struct node *next;
struct node *prev;
};

struct linked_list
{
size_t size;
struct node *tail;
struct node *head;
};

static struct linked_list *linked_list_new(void)
{
struct linked_list *list = malloc(sizeof *list);
list->size = 0;
list->head = NULL;
list->tail = NULL;
return list;
}

static void linked_list_add(struct linked_list *list,
int value)
{
struct node *new_node = malloc(sizeof *new_node);
struct node *list_tail = list->tail;

new_node->prev = list_tail;
new_node->next = NULL;
new_node->value = value;

if (list_tail) {
list_tail->next = new_node;
}
else {
list->head = new_node;
}

list->tail = new_node;
list->size++;
}

static void linked_list_free(struct linked_list *list)
{
struct node *node = list->head;

if (list->size > 0) {
while (node->next) {
node = node->next;
free(node->prev);
}

free(node);
}

free(list);
}

static int min_element(const struct linked_list *list)
{
int min;
struct node *tmp = list->head;

if (list->size < 0) {
return -1;
}
else {
min = tmp->value;
}

while (tmp->next) {
tmp = tmp->next;

if (tmp->value < min) {
min = tmp->value;
}
}

return min;
}

int main(void)
{
struct linked_list *list = linked_list_new();
struct node *tmp;
size_t count;

srand(time(NULL));

printf("Number of elements: ");
scanf("%u", &count);

while (count--) {
linked_list_add(list, rand() % 100 - 50);
}

tmp = list->head;

while (tmp) {
printf("%d ", tmp->value);
tmp = tmp->next;
}

printf("\nMin. element: %d\n", min_element(list));

linked_list_free(list);
return 0;
}
Сергей Кашин
Сергей Кашин
1 893
Лучший ответ
Юрий Танаков спасибо большое за объяснение и реализацию, только не могу понять хотел проверить ваш код и там ошибка
Сергей Кашин
 // ...
struct linked_list *list = (struct linked_list*) malloc(sizeof *list);
// ...
struct node *new_node = (struct node *) malloc(sizeof *new_node);
// ...
На, вдохновляйся:
https://pastebin.com/5sVGm5ww