Вы можете сделать что-то вроде этого, чтобы добавить узел в отсортированный список:
node * add_node_to_sort_list(node * list, node * newNode)
{
/* should the node be inserted as the head? */
if( list == NULL || strncmp(list->name, newNode->name, 100) < 0 )
{
newNode->next = list;
return newNode;
}
/* search for the location the node should be at */
while(list->next != NULL && strncmp(list->next->name, newNode->name) > 0 )
{
/* move to the next node */
list = list->next;
}
/* we have found the spot to insert the node */
newNode->next = list->next;
list->next = newNode;
return list;
}
Используя это для обновления вашего кода:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a doubly linked list type
typedef struct node {
char name[100];
int age;
float weight;
struct node *next;
} node;
void print_list(node* list) {
// walk the list to print out the contents
while(list != NULL)
{
printf("%s%d\n%f\n", list->name, list->age, list->weight);
list = list->next;
}
}
node* new_node(char *value, int a, float w) {
node* t = (node *)malloc(sizeof(node));
strcpy(t->name, value);
t->age = a;
t->weight = w;
t->next = NULL;
return t;
}
node * add_node_to_sort_list(node * list, node * newNode)
{
/* should the node be inserted as the head? */
if( list == NULL || strncmp(list->name, newNode->name, 100) > 0 )
{
newNode->next = list;
return newNode;
}
/* search for the location the node should be at */
while(list->next != NULL && strncmp(list->next->name, newNode->name, 100) < 0 )
{
/* move to the next node */
list = list->next;
}
/* we have found the spot to insert the node */
newNode->next = list->next;
list->next = newNode;
return list;
}
node* add(node* list) {
char name[100];
int a;
float w;
printf("Enter name: ");
fgets(name, 100, stdin);
printf("Enter age: ");
scanf("%d", &a);
printf("Enter weight: ");
scanf("%f", &w);
while (getchar() != '\n');
node* s = new_node(name, a, w);
return add_node_to_sort_list(list, s);
}
int getChoice() {
int ch;
printf("1. Add a Record\n2. Display All Records\n");
printf("3.Quit\nEnter choice: ");
scanf("%d", &ch);
while (getchar() != '\n');
return ch;
}
int main() {
node* my_list = NULL;
int ch;
while ((ch = getChoice()) != 3) {
if (ch == 1) {
my_list = add(my_list);
}
else if (ch == 2) {
print_list(my_list);
}
printf("\n");
}
}