首页 > 解决方案 > 如何创建一个函数来执行节点删除

问题描述

我的功能deleteStates不是删除节点。

Please any advice on what to improve on my function `deleteStates`. 

    ```#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
#include <iomanip>
using namespace std;

//STRUCT
struct ListNode // ListNode is a struct, but remember, in C++ a struct, by convention, has no more than a single constructor function.
                // The C language has struct data types, but not classes. C++ has classes usually with additional member functions.
  {
     string state;
      int Totpop;
      int Elder;
      double percent;
     ListNode *next;
     // Constructor
     ListNode(string value1,int tot, int eld, double per, ListNode *next1 = nullptr) // Constructor function inside (inline in) the struct definition
     {
       state = value1;
         Totpop = tot;
         Elder = eld;
         percent = per;
       next = next1;
     }
  };
// Function prototypes
int size(ListNode *);
void displayList(ListNode *);
void outfile (ListNode *, string);
void writeData (ListNode *, string);
void findState (ListNode *, char);
void deleteState (ListNode *, char);
//MAIN
int main(){
   ListNode *numberList = nullptr;    // List of numbers
   string state;                  // Used to read the file
    int total = 0;
    int elders = 0,ind1,ind2;
    double percent = 0.0,number;
    string space = "";
    char remove;
   // Open the file
   ifstream file("CensusData.csv");
   if (!file)
   {
        cout << "Error in opening the file of numbers.";
        exit(1);
   }else{
   // Read the file into a linked list
   while (getline(file, state))
   {
       string delimiter = ",";
       space += string (1, state[0]) + ",";
       size_t ind = 0;
       string check;
       int h = 1;
       while ((ind = state.find (",")) != string::npos)
         {
           check = state.substr (0, ind);
           state.erase (0, ind + delimiter.length ());
           if (h == 1)
             {
               state = check;
               h++;
             }
           else if (h == 2)
             {
               ind1 = atoi (check.c_str ());
               h++;
             }
           else if (h == 3)
             {
               ind2 = atoi (check.c_str ());
               h++;
             }
           else if (h == 4)
             {
               number = atof (check.c_str ());
               h++;
             }
         }
       // Create a node to hold this number.
       numberList = new ListNode(state,total,elders,percent, numberList);
   }
   // Print the list
   cout << endl << "The contents of the list are: " << endl;
   displayList(numberList);

   // Print the size of the list
   cout << endl << "The number of items in the list is: "
        << size(numberList)<<endl;
  //Print state name, memory addresses, and memory address of the "next" node
   writeData(numberList,"CensusNodes.txt" );
  //Find the state by letter
       cout << endl << "Enter the first letter of the state(In UPPERCASE): ";
       string letter;
       cin >> letter;
       if (space.find (letter) != string::npos)
         {
           cout << "States are: ";
           findState (numberList, letter[0]);
           cout << endl;
             cout<<"Would you like to remove these states? Y / N : ";
             cin>>remove;
             switch (remove) {
                 case 'Y':deleteState(numberList, letter[0]);
                 case 'y':deleteState(numberList, letter[0]);
                     break;
                 case 'N':cout<<"Not deleted"<<endl;
                 case 'n':cout<<"Not deleted"<<endl;
                     break;
             }
         }
       else
         {
           cout << "There are no states with that letter.";
         }
   return 0;
   }
}

//*****************************************
// length computes the number of nodes in *
// a linked list                          *
//*****************************************
int size(ListNode *ptr)
{
  if (ptr == nullptr)
    return 0;
  else
   return 1 + size(ptr->next);
}

//*******************************************
// displayList prints all the values stored *
// in the list                              *
//*******************************************
void displayList(ListNode *ptr)
{
  if (ptr != nullptr)
    {
      cout << ptr-> state << " -> ";
      displayList(ptr->next);
    }
}
//*********Output data into a new file***********
void writeNewFile (ListNode * ptr, string outfile)
{
  ofstream ExitFile (outfile);
  while (ptr != nullptr)
    {
      ExitFile << ptr->state << "," << ptr->Totpop << "," << ptr->
        Elder << "," << ptr->percent << endl;
      ptr = ptr->next;
    }
}
//********* write the name and memory address of each ******
//********* pointers                                  ******
//**********************************************************
void writeData (ListNode * ptr, string outfile)
{
  ofstream ExitFile (outfile);
  while (ptr != nullptr)
    {
      ExitFile <<setw(30)<< ptr->state << ", " << &ptr->state <<setw(20)<<" --Next Node memory address: "<<&ptr->next<<endl;
      ptr = ptr->next;
    }
    ExitFile << "----------------------------End of the Original Node List-------------------------------"<<endl;
}
//********* Find states with the letter input *****
//**********************************************************
void findState (ListNode * ptr, char a)
{
  if (ptr != nullptr)
    {
      if (ptr->state[0] == a)
        cout << ptr->state << " ->";
      findState (ptr->next, a);
    }
}
//********* Delete states with the letter input **************
//**********************************************************
void deleteState(ListNode * ptr, char a){
    cout<<"Would you like to delete these states?\n";
    while(ptr != NULL){
           if(ptr->state.compare(nameToDelete)==0){
               ListNode *temp = ptr;
               ptr = ptr->next;
               free (temp);
               cout<<"Deletion successfully\n";
           }
        }
}

标签: c++stringlinked-listsingly-linked-listfunction-definition

解决方案


函数deleteState定义如下

void deleteState(ListNode * ptr, char a){
    cout<<"Would you like to delete these states?\n";
    while(ptr != NULL){
           if(ptr->state.compare(nameToDelete)==0){
               ListNode *temp = ptr;
               ptr = ptr->next;
               free (temp);
               cout<<"Deletion successfully\n";
           }
        }
}

没有意义。对于初学者,a不使用该参数。另一方面,使用了未声明的变量nameToDelete

还要删除使用new您正在使用 C 函数的运算符创建的节点free

据我了解,您需要编写一个递归函数来删除列表中数据成员state从指定字母开始的所有节点。

如果是这样,那么该功能可以采用以下方式之一

ListNode * deleteState( ListNode * ptr, char c )
{
    if ( ptr != nullptr )
    {
        if ( ptr->next != nullptr ) ptr->next = deleteState( ptr->next, c );
        if ( ptr->state[0] == c )
        {
            ListNode *temp = ptr;
            ptr = ptr->next;
            delete temp;
        }
    }

    return ptr;
}   

或者

ListNode * deleteState( ListNode *ptr, char c )
{
    if ( ptr != nullptr )
    {
        if ( ptr->state[0] == c )
        {
            ListNode *temp = ptr;
            ptr = ptr->next;
            delete temp;
            
            ptr = deleteState( ptr, c );
        }
        else
        {
            ptr->next = deleteState( ptr->next, c );
        }
    }
    
    return ptr;
}

并称为

numberList = deleteState( numberList, letter[0] );

并重写这些案例标签

 case 'Y':deleteState(numberList, letter[0]);
 case 'y':deleteState(numberList, letter[0]);
     break;

至少喜欢

 case 'Y':
 case 'y':
     deleteState(numberList, letter[0]);
     break;

推荐阅读