1

Нужно изменить указатели так, чтобы первый и последний элементы списка поменялись местами. Для получения указателя на последний элемент списка есть функция getLastP. Подскажите, как правильно реализовать функцию swap. Вот код:

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_WARNINGS

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <Windows.h>
#include <locale>

char count = 0;
size_t length;
bool b = true;

typedef struct date {
    char day;
    char month;
    short year;
}date;
typedef struct newspapers {
    char name[25];
    short number;
    date date1;
    char printingOffice[25];
    newspapers *next;
}newspapers;

void addNewspaper(newspapers **head, char name[25],
    short number, char day, char month,
    short year, char printingOffice[25]) { // добавление нового элемента
    newspapers *tmp = (newspapers*)malloc(sizeof(newspapers));
    strcpy(tmp->name, name);
    tmp->number = number;
    tmp->date1.day = day;
    tmp->date1.month = month;
    tmp->date1.year = year;
    strcpy(tmp->printingOffice, printingOffice);

    tmp->next = (*head);
    (*head) = tmp;
    count++;
    b = false;
}
void insert(newspapers *head, unsigned n, char name[25],
    short number, char day, char month,
    short year, char printingOffice[25]) {
    unsigned i = 0;
    newspapers *tmp = NULL;
    while (i < n && head->next) {
        head = head->next;
        i++;
    }
    tmp = (newspapers*)malloc(sizeof(newspapers));
    strcpy(tmp->name, name);
    tmp->number = number;
    tmp->date1.day = day;
    tmp->date1.month = month;
    tmp->date1.year = year;
    strcpy(tmp->printingOffice, printingOffice);
    if (head->next) {
        tmp->next = head->next;
    }
    else {
        tmp->next = NULL;
    }
    head->next = tmp;
    count++;
}

newspapers* getLastP(newspapers *head) {
    if (head == NULL) {
        return NULL;
    }
    while (head->next) {
        head = head->next;
    }
    return head;
}
/*newspapers* swap(newspapers *head) {
    newspapers *last = getLastP(head);
    newspapers *tmp = (newspapers*)malloc(sizeof(newspapers));
    tmp = head;
    head = last;
    last = tmp;
    return head;
}*/
void printLinkedList(newspapers *head) {

    while (head) {
        length = strlen(head->name);
        if (length > 0 && head->name[length - 1] == '\n')
            head->name[length - 1] = '\0';

        length = strlen(head->printingOffice);
        if (length > 0 && head->printingOffice[length - 1] == '\n')
            head->printingOffice[length - 1] = '\0';

        printf("| %-15s ", head->name);
        printf("| %-8d ", head->number);
        printf("| %2d.%2d.%4d     ", head->date1.day, head->date1.month, head->date1.year);
        printf("| %-15s|\n", head->printingOffice);

        head = head->next;
    }
    printf("\n");
}

void main() {
    setlocale(LC_ALL, "Russian");
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);

    char c = '1';
    char name[25],number = 0, day = 0, month = 0, printingOffice[25];
    short year = 0;

    newspapers *head = NULL;//указатель на первый элемент списка

    while (c != '0') {
        printf("Введите название газеты %d: ", count + 1);
        fgets(name, sizeof name, stdin);

        printf("Введите номер выпуска %d: ", count + 1);
        scanf("%hhd", &number);

        printf("Ввод даты выпуска %d \n", count + 1);
        printf("Введите день: ");
        scanf("%hhd", &day);
        printf("Введите месяц: ");
        scanf("%hhd", &month);
        printf("Введите год: ");
        scanf("%hd", &year);

        printf("Введите издательство %d: ", count + 1);
        getchar();
        fgets(printingOffice, sizeof printingOffice, stdin);
        if(b)addNewspaper(&head, name, number, day, month, year, printingOffice);
        else insert(head, 7, name, number, day, month, year, printingOffice);

        puts("Чтобы закончить ввод, введите 0, чтобы продолжить, нажмите любую клавишу");
        scanf("%c", &c);
    }
    printf("_______________________________________________________________\n");
    printf("|          Газеты            |                |                |\n");
    printf("|____________________________|  Дата выпуска  |  Издательство  |\n");
    printf("|    Название     |  Номер   |                |                |\n");
    printf("|-----------------|----------|----------------|----------------|\n");
    printLinkedList(head);
    printf("|--------------------------------------------------------------|");

    getch();
}

1 ответ 1

0

Если вам нужно поменять первый узел с последним, то

  1. вы должны иметь ссылку на последний узел
  2. первый узел также должен передаваться по ссылке.

Поэтому сначала вы должны написать функцию, которая ищет указатель на последний узел.

Она может выглядеть следующим образом

newspapers ** getLastP(newspapers **head)
{
    if (*head != NULL)
    {
        while ((*head)->next != NULL) head = &(*head)->next;
    }

    return head;
}

Тогда функция swap может выглядеть следующим образом

void swap(newspapers **head)
{
    if (*head != NULL && (*head)->next != NULL)
    {
        newspapers **last = getLastP(head);

        newspapers *new_head = *last;

        if ((*head)->next == new_head)
        {
            new_head->next = *head;
            *last = NULL;
        }
        else
        {
            new_head->next = (*head)->next;
            *last = *head;
            (*last)->next = NULL;
        }

        *head = new_head;
    }
}

Ниже представлена демонстрационная программа.

#include <stdio.h>
#include <stdlib.h>

typedef struct newspapers
{
    int data;
    struct newspapers *next;
} newspapers;

int addNewspaper(newspapers **head, int data)
{
    newspapers *tmp = malloc(sizeof(newspapers));
    int success = tmp != NULL;

    if (success)
    {
        tmp->data = data;
        tmp->next = *head;

        *head = tmp;
    }

    return success;
}

newspapers ** getLastP(newspapers **head)
{
    if (*head != NULL)
    {
        while ((*head)->next != NULL) head = &(*head)->next;
    }

    return head;
}

void swap(newspapers **head)
{
    if (*head != NULL && (*head)->next != NULL)
    {
        newspapers **last = getLastP(head);

        newspapers *new_head = *last;

        if ((*head)->next == new_head)
        {
            new_head->next = *head;
            *last = NULL;
        }
        else
        {
            new_head->next = (*head)->next;
            *last = *head;
            (*last)->next = NULL;
        }

        *head = new_head;
    }
}

void printNewspapers(newspapers *head)
{
    for (; head != NULL; head = head->next) printf("%d ", head->data);
}



int main()
{
    const int N = 10;
    newspapers *head = NULL;

    for (int i = N; i != 0 && addNewspaper(&head, i); i--)
    {
        printNewspapers(head);
        printf("\n");

        swap(&head);

        printNewspapers(head);
        printf("\n\n");
    }

    return 0;
}

Ее вывод на консоль следуюший

10
10

9 10
10 9

8 10 9
9 10 8

7 9 10 8
8 9 10 7

6 8 9 10 7
7 8 9 10 6

5 7 8 9 10 6
6 7 8 9 10 5

4 6 7 8 9 10 5
5 6 7 8 9 10 4

3 5 6 7 8 9 10 4
4 5 6 7 8 9 10 3

2 4 5 6 7 8 9 10 3
3 4 5 6 7 8 9 10 2

1 3 4 5 6 7 8 9 10 2
2 3 4 5 6 7 8 9 10 1

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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