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

Я реализовал отсортированный двусвязный список с помощью указателей на С++. Я хочу отобразить сообщение об ошибке при удалении последнего элемента, в котором говорится, что "двухсвязный список пуст, не может удалить больше элементов", а также отобразить сообщение перед удалением последнего element говорит «последний элемент в узле, вы уверены, что хотите его удалить»?

#include "stdafx.h"
#include "DoublyLinkedList.h"

#include<iostream>
using namespace std;

DoublyLinkedList::DoublyLinkedList():Head(nullptr),Tail(nullptr) {

}

DoublyLinkedList::~DoublyLinkedList() {

    Node *current = Head;
    while (current != NULL)
    {
    Node* next = current->Next;   //The objects pointed to by head and tail at the beginning of the destructor are deleted         
        Node* prev = current->Prev;     //  through the current pointer. Then they are deleted again at the                                                               end of the destructor.
        delete current;
        current = next;
        current = prev;
    }



}
void DoublyLinkedList::SortedInsert(const int& new_element) {


    if(new_element !=0){
        Node* np = new Node(new_element);
    if (!Head)
    {
        Head = np;
        Tail = np;
    }
    else if (new_element < Head->Element)
    {
        np->Next = Head;
        Head->Prev = np;
        Head = np;
    }
    else
    {
        Node *cur = Head->Next;
        while ((cur) && (new_element >= cur->Element))
            cur = cur->Next;

        if (cur)
        {
            np->Prev = cur->Prev;
            np->Next = cur;
            cur->Prev->Next = np;
            cur->Prev = np;
        }
        else
        {
            Tail->Next = np;
            np->Prev = Tail;
            Tail = np;
        }
        }
    }
}

void DoublyLinkedList::Delete(const int& del_element)
{
    Node *cur = Head;
    while (cur)
    {
        if (cur->Element == del_element)
        {
            if (cur->Prev)
                cur->Prev->Next = cur->Next;
            if (cur->Next)
                cur->Next->Prev = cur->Prev;
            if (cur == Head)
                Head = cur->Next;
            if (cur == Tail)
                Tail = cur->Prev;
            delete cur;
            break;
        }
        cur = cur->Next;



    }
}

void DoublyLinkedList::traverse_head() {
    Node *t = Head;
    while (t != NULL)
    {
        cout << t->Element << "\t";

        t = t->Next;
    }

    cout << endl;
}

void DoublyLinkedList::traverse_tail() {


    Node *temp = Tail;
    while (temp != NULL) {
        cout << temp->Element << "\t";
        temp = temp->Prev;
    }
}
main.cpp

// Question1.cpp : определяет точку входа для консольного приложения. //

#include "stdafx.h"
#include"DoublyLinkedList.h"
#include<iostream>

using namespace std;


    int main()
    {

        DoublyLinkedList intlist;

        int i = 0, x=0,delete_elm=0;

        //intlist.SortedInsert(3);
        //intlist.SortedInsert(6);
        //intlist.SortedInsert(7);
        //intlist.SortedInsert(10);
        //intlist.SortedInsert(-1);

        //intlist.traverse_head();

        do
        {
            cout << "\nEnter value of node.Press 0 to stop\n";
            cin >> x;


            if ((!cin) || cin.peek() != '\n') {

                cin.clear();
                    cin.ignore(numeric_limits<streamsize>::max(), '\n');
                    cout << "Invalid input, no string allowed!!" << endl;
            }
            else {
                intlist.SortedInsert(x);
                i++;
            }
        } while (x != 0);
        intlist.traverse_head();

        cout << "\nTraversing Doubly Linked List head first\n";
        intlist.traverse_head();
        cout << "\nTraversing Doubly Linked List tail first\n";
        intlist.traverse_tail();
        cout << endl;
        do {
            cout << "Which element do you want to delete? 0 to stop delete operation" << endl;
            cin >> delete_elm;
            cout << endl;
            if ((!cin) || cin.peek() != '\n' || x < 0) {

                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout << "Invalid input, no string allowed!!" << endl;
            }
            else {

                intlist.Delete(delete_elm);
                cout << "\nTraversing Doubly Linked List head first\n";
                intlist.traverse_head();
                cout << "\nTraversing Doubly Linked List tail first\n";
                intlist.traverse_tail();
                cout << endl;
            }
        } while (delete_elm != 0);

        system("pause");
        return 0;
    }

person user5444454333    schedule 17.03.2018    source источник


Ответы (1)


Поскольку вы, похоже, не используете фиктивные узлы, проверка того, что список пуст, аналогична проверке того, являются ли указатели Head или Tail нулевыми. Проверка того, что это только один элемент, аналогична проверке того, является ли Head->Next нулевым (конечно, сначала убедитесь, что Head не является нулевым).
В качестве альтернативы вы можете поддерживать переменную size (увеличивается при вставке и уменьшается при удалении). ) или напишите метод для вычисления размера путем обхода списка.

person Mike P    schedule 17.03.2018
comment
Правильно ли это? if (cur-›Next == NULL || cur-›Prev == NULL) { cout ‹‹ Удаление последнего элемента в списке ‹‹ endl; } if (Head == NULL || Tail == NULL) { cout ‹‹ Список пуст ‹‹ endl; } - person user5444454333; 18.03.2018
comment
Я пишу это под if (cur-›Element == del_element){ } - person user5444454333; 18.03.2018
comment
Мне это кажется почти нормальным; первое условие выглядит так, как будто оно сработает в любом конце списка, независимо от размера. (PS: я бы не стал ничего печатать внутри своей реализации двусвязного списка, хотя я не знаю вашего проекта.) - person Mike P; 18.03.2018