C++指针实现排序双向链表:删除元素提示消息实现问询
Alright, let's tackle this step by step. You've already got a sorted doubly linked list implemented with pointers in C++, and you need to add two specific messages for deletion scenarios: a confirmation prompt when deleting the very last element, and an error message when trying to delete from an empty list.
First, let's fill in the missing parts of your code and implement the required logic. I'll assume your DoublyLinkedList class has the basic structure, and we'll focus on the deleteLast() method since that's where the prompts need to go.
1. Complete the Node Structure and Class Declaration (in DoublyLinkedList.h)
#pragma once #include <iostream> using namespace std; struct Node { int data; Node* prev; Node* next; Node(int val) : data(val), prev(nullptr), next(nullptr) {} }; class DoublyLinkedList { private: Node* Head; Node* Tail; public: DoublyLinkedList() : Head(nullptr), Tail(nullptr) {} ~DoublyLinkedList() { // Clean up remaining nodes to avoid memory leaks while (Head != nullptr) { Node* temp = Head; Head = Head->next; delete temp; } } void deleteLast(); // Add your existing methods (like insert, display, etc.) here };
2. Implement the deleteLast() Method (in your .cpp file)
#include "stdafx.h" #include "DoublyLinkedList.h" void DoublyLinkedList::deleteLast() { // Scenario 1: List is empty - show error message if (Head == nullptr) { cout << "doubly linked list is empty cannot delete any more elements" << endl; return; } // Check if we're about to delete the last remaining element bool isLastElement = (Head == Tail); if (isLastElement) { // Show confirmation prompt before deleting the last element cout << "the last element in the node are you sure you want to delete it (y/n): "; char userChoice; cin >> userChoice; // Only proceed if user confirms (case-insensitive) if (tolower(userChoice) != 'y') { cout << "Deletion cancelled." << endl; return; } // Delete the last node and reset head/tail delete Head; Head = nullptr; Tail = nullptr; cout << "Last element deleted successfully." << endl; } else { // Normal deletion of non-last tail node Node* temp = Tail; Tail = Tail->prev; Tail->next = nullptr; delete temp; cout << "Last element deleted successfully." << endl; } }
Key Details Explained
- Empty List Check: We first check if
Headisnullptr(since if the list is empty, bothHeadandTailwill benullptr). If so, we immediately show the error message and exit the function. - Last Element Confirmation: When
HeadandTailpoint to the same node, that means we're about to delete the only remaining element. We prompt the user for confirmation, and only proceed if they enter 'y' or 'Y'. - Memory Management: We make sure to properly deallocate memory for deleted nodes and reset
Head/Tailwhen the last element is removed to avoid dangling pointers.
You can integrate this deleteLast() method into your existing codebase, and it will handle both required scenarios exactly as you specified.
内容的提问来源于stack exchange,提问作者user5444454333

