1

Необходимо реализовать добавление новых элементов таким образом, чтобы элементы сохранялась упорядоченность списка по номеру рейса

Пробовал использовать такой алгоритм, но не могу разобраться с указателями

        struct node* current;
        current = first;

        if (first->flight.flightNumber < tmp->flight.flightNumber)
        {
            last = tmp;
            tmp->next = first;
        }

        else
        {
            while (current->next != NULL && first->flight.flightNumber > tmp->flight.flightNumber)
            {
                current = current->next;
            }

            tmp->next = current->next;
            current->next = tmp;
        } 

Основной код:

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define M 100
#define LEN 4

struct Aeroflot
{
    char destination[M];        // пункт назначения
    int flightNumber;           // номер рейса
    char aircraftType[M];       // тип самолета
};

struct node
{
    struct Aeroflot flight;

    struct node* next;
    struct node* prev;
};

struct node* first = NULL;
struct node* last = NULL;

int main()
{
    int continuation = 0; // Костыль для прерывания цикла
    int count = 1; // Счетчик для введенного количества элементов
    for (int i = 0; i < LEN; i++) 
    {       
        count++;
        char buf[100];
        printf("Enter destination: \n");  // Ввод пункта назначения
        scanf_s("%s", buf, 100);

        int numberOfFlight;
        printf("Enter flight number: \n");  // Ввод номера рейса
        scanf_s("%d", &numberOfFlight);

        char bufSecond[100];
        printf("Enter the type of aircraft: \n"); // Ввод типа самолета
        scanf_s("%s", bufSecond, 100);

        if (first == NULL)
        {
            first = malloc(sizeof(struct node));
            last = first;

            first->next = NULL;
            first->prev = NULL;

            strcpy(first->flight.destination, buf);
            first->flight.flightNumber = numberOfFlight;
            strcpy(first->flight.aircraftType, bufSecond);
            continue;
        }

        struct node* tmp = malloc(sizeof(struct node));

        tmp->next = NULL;
        tmp->prev = last;
        last->next = tmp;
        last = tmp;

        strcpy(last->flight.destination, buf);
        last->flight.flightNumber = numberOfFlight;
        strcpy(last->flight.aircraftType, bufSecond);

        printf("Enter 1 if you want to stop typing or any other number to continue\n");  // Если вводим 1, то выходим из цикла, если другое число, то продолжаем
        scanf_s("%d", &continuation);
        if (continuation == 1)
        {
            break;
        }

    } 
    
    /*Вывод c начала*/
    struct node* tmp = first;
    while (tmp != NULL)
    {
        printf("destination: %s || flightNumber: %i || aircraftType: %s \n", tmp->flight.destination, tmp->flight.flightNumber, tmp->flight.aircraftType);
        tmp = tmp->next;
    }
    
    continuation = 0;
    char flightSearch[100]; // Переменная для искомого слова
    do // ***** "Бесконечный" поиск рейса
    {
        struct node* tmp = first;
        printf("\nEnter the destination you are looking for: \n");
        scanf_s("%s", flightSearch, 100);
        printf("List of destinations %s found  : \n", flightSearch);
        int z = 0;
        
        while(tmp != NULL)
        {
            if (strcmp(flightSearch, tmp->flight.destination) == 0) // Сравниваем строки введенного слова и слова из структуры пока, если есть совпадение, то выводим
            {
                z++;
                printf("Flight Number: %d  \n", tmp->flight.flightNumber);
                printf("Aircraft Type: %s \n", tmp->flight.aircraftType);

            }
            tmp = tmp->next;
        }
        if (z == 0) // Если совпадений не нашлось 
        {
            printf("\nNo flights with that name");
        }
        printf("\nEnter 1 if you want to stop typing or any other number to continue\n");  // Если вводим 1, то выходим из цикла, если другое число, то продолжаем
        scanf_s("%d", &continuation);
    } while (continuation != 1); // ***** пока не переменная != 1 

    /*Очистка памяти*/
    while (first != NULL)
    {
        struct node* tmp = first;
        first = first->next;

        free(tmp);
    }
    last = NULL;

    return 0;
}
1
  • Side note: двусвязные списки лучше реализовывать на макросах, код будет несколько чище и понятнее (примеры: pastebin.com/TwN3SiCd, pastebin.com/vsQG1bPS).
    – 0andriy
    22 мая 2021 в 9:14

1 ответ 1

0

Задача сводится к такой : найти место в списке, где один элемент меньше а следующий нет. Делаем простой цикл :

void  pushAeroflot  ( struct Aeroflot const aer ) {
  struct node * tmp = malloc  ( sizeof (  struct node ) ) ;
  tmp ->  flight  = aer ;
  // ---
  struct node* prevcurrent = NULL ;
  struct node* current;
  current = first;
  int const fn = tmp->flight.flightNumber ;
  while (current) {
    if (current->flight.flightNumber < fn) {
      // если ещё меньше, двигаемся вперёд
      prevcurrent = current ;
      current = current -> next ; }
    else {
      // если нашли не меньше, возвращаемся назад и останавливаемся
      current = prevcurrent ;
      break ; } }
  if (current) {
    // добавляем в середину
    tmp -> next = current -> next ;
    current -> next = tmp ;
    tmp->prev = current;
    tmp -> next -> prev = tmp ; }
  else {
    if (prevcurrent) {
      // добавляем в конец
      prevcurrent ->next = tmp ;
      tmp -> next = NULL ;
      tmp -> prev = prevcurrent ;
      last = tmp ; }
    else {
      // добавляем в начало
      tmp -> next = first ;
      tmp -> prev = NULL ;
      if (first == NULL)
        last = tmp ;
      first = tmp ; } }
  // ---
  }

main.c :

    struct Aeroflot aer ;
    
    printf("Enter destination: \n");  // Ввод пункта назначения
    scanf ( "%99s"  , & ( aer . destination [ 0 ] ) ) ;

    printf("Enter flight number: \n");  // Ввод номера рейса
    scanf("%d", & aer . flightNumber);

    printf("Enter the type of aircraft: \n"); // Ввод типа самолета
    scanf("%99s", & ( aer . aircraftType [ 0 ] ) ) ;

    pushAeroflot  ( aer ) ;
1
  • Side note: откуда этот ужасный стиль с пробелом перед ;?
    – 0andriy
    22 мая 2021 в 9:10

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.