Удаление n-го элемента из списка(С++)

Рейтинг: 0Ответов: 1Опубликовано: 13.05.2023

Дана следующая задача:

Написать программу для удаления узла из любой позиции двусвязного списка, его создания и вывода на экран. Программа должна запрашивать количество узлов при создании, их значения и позицию удаляемого элемента. Список создается путем добавления элемента в начало списка. Функция вывода реализует отображение списка начиная с конечного элемента. Нумерация позиций начинается с 1, 1-ый элемент – начальный элемент списка.

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

#include <iostream>


struct LIST
{
    int data;
    LIST* next;
    LIST* prev;
};


void create_an_list(LIST** head, LIST** tail);
void print_the_list(LIST* tail);
LIST* define_an_element(LIST* head);
void delete_an_element(LIST** ptr);


int main()
{
    LIST* head = NULL; LIST* tail = NULL;
    int n;
    std::cin >> n;
    std::cout << std::endl;
    for (int i = 1; i <= n; i++)
        create_an_list(&head, &tail);
    std::cout << std::endl;
    LIST *ptr = define_an_element(head);
    std::cout << ptr->data;
    delete_an_element(&ptr);
    print_the_list(tail);
    return 0;
}


void create_an_list(LIST** head, LIST** tail)
{
    LIST* temp;
    temp = new LIST;
    std::cin >> temp->data;
    temp->next = NULL;
    temp->prev = NULL;
    if (*head == NULL)
    {
        *head = temp;
        *tail = temp;
    }
    else
    {
        temp->next = *head;
        (*head)->prev = temp;
        *head = temp;
    }
}

LIST* define_an_element(LIST* head)
{
    int pos, cnt = 0;
    std::cin >> pos;
    std::cout << std::endl;
    LIST* temp;
    temp = head;
    if (temp != NULL)
    {
        while (temp != NULL)
        {
            cnt++;
            if (cnt == pos + 1)
                return temp;
            temp = temp->next;
        }
    }
    return NULL;
}


void delete_an_element(LIST** ptr)
{
    LIST* temp = (*ptr)->prev;
    if (temp != NULL)
    {
        (*ptr)->prev = temp->prev;
        if (temp->prev)
            (*ptr)->prev->next = *ptr;
    }
}


void print_the_list(LIST* tail)
{
    LIST* temp;
    temp = tail;
    while (temp != NULL)
    {
        std::cout << temp->data << " ";
        temp = temp->prev;
    }
}

В коде была описка. Убрал ; после начала цикла. Но возникла новая проблема. При вводе 123 и выборе 3 элемента выдает пустую строку.

Ответы

▲ 0Принят
#include <iostream>


struct LIST
{
    int data;
    LIST* next;
    LIST* prev;
};


void create_an_list(LIST** head, LIST** tail);
void print_the_list(LIST* tail);
void delete_of_tail(LIST** head, LIST** tail);
void delete_of_head(LIST** head, LIST** tail);
LIST* define_an_element(LIST* head, int pos);
void delete_after(LIST** ptr);


int main()
{
    LIST* head = NULL, *tail = NULL, *ptr = NULL;
    int size, position;
    std::cin >> size;
    std::cout << std::endl;
    for (int i = 1; i <= size; i++)
        create_an_list(&head, &tail);
    std::cout << std::endl;
    std::cin >> position;
    if (position == 1)
    {
        delete_of_head(&head, &tail);
    }
    if (position == size)
    {
        delete_of_tail(&head, &tail);
    }
    if (position < size && position > 1)
    {
        ptr = define_an_element(head, position);
        delete_after(&ptr);
    }
    print_the_list(tail);
    return 0;
}


void create_an_list(LIST** head, LIST** tail)
{
    LIST* temp;
    temp = new LIST;
    std::cin >> temp->data;
    temp->next = NULL;
    temp->prev = NULL;
    if (*head == NULL)
    {
        *head = temp;
        *tail = temp;
    }
    else
    {
        temp->next = *head;
        (*head)->prev = temp;
        *head = temp;
    }
}


void delete_of_head(LIST** head, LIST** tail)
{
    if (*head != *tail)
    {
        LIST* temp = *head;
        *head = (*head)->next;
        (*head)->prev = NULL;
        delete (temp);
    }
    else
    {
        *head = NULL;
        *tail = NULL;
    }
}

void delete_of_tail(LIST** head, LIST** tail)
{
    LIST* temp = *head;
    if (*tail != *head)
    {
        while (temp->next != *tail)
            temp = temp->next;
        delete* tail;
        *tail = temp;
        (*tail)->next = NULL;
    }
    else
    {
        *tail = NULL;
        *head = NULL;
    }
}

LIST* define_an_element(LIST* head, int pos)
{
    int cnt = 0;
    std::cout << std::endl;
    LIST* temp;
    temp = head;
    if (temp != NULL)
    {
        while (temp != NULL)
        {
            cnt++;
            if (cnt == pos - 1)
                return temp;
            temp = temp->next;
        }
    }
    return NULL;
}


void delete_after(LIST** ptr)
{
    struct LIST* temp = (*ptr)->next;
    if (temp != NULL)
    {
        struct LIST* next_ptr = temp->next;
        (*ptr)->next = next_ptr;
        if (next_ptr)
            next_ptr->prev = *ptr;
    }
    else
        (*ptr)->next = NULL;
}


void print_the_list(LIST* tail)
{
    LIST* temp;
    temp = tail;
    while (temp)
    {
        std::cout << temp->data << " ";
        temp = temp->prev;
    }
}