All my other functions of my doubly linked list which consist of Account class and Node class are all working except this last function.
The function bool deleteAcc(string name) will take as it’s argument, the string name (that the user inputs) and returns a bool result. It will then find the name in the list and delete the corresponding Account (and Node) from the list, then return True. If the Account was not in the list, it will return False.
This is my code as shown below:
#include <iostream>
#include "Account.h"
#include <string>
#include "Node.h"
using namespace std;
bool deleteAcc(const string name1);
int main(){
string name;
int k;
cout << "How many accounts do you want to enter? ";
cin >> k;
Node* head = NULL;
//Node* tail = NULL;
for (int i = 0; i < k; i++) {
string name;
double balance;
cout << "Enter account name: ";
cin >> name;
cout << "Enter account balance: ";
cin >> balance;
Account account(name, balance);
Node* newNode = new Node(account);
if (head == NULL) {
// The list is empty, so set both head and tail to the
// new node
head = newNode;
// tail = newNode;
} else {
// The list is not empty, so add the new node to the
// tail
newNode->setNext(head);
//newNode->setPrevious(head); // Update previous pointer
// of newNode to point to the previous last node (i.e.,
// tail)
head = newNode;
}
}
// Print the list
cout << "Account balances:" << endl;
cout << endl;
Node* currentNode = head;
while (currentNode != NULL) {
cout << currentNode->getData() << endl;
currentNode = currentNode->getNext();
}
cout << "Enter the account name you want to delete: ";
cin >> name;
deleteAcc(name);
// Deallocate memory
currentNode = head;
while (currentNode != NULL) {
Node* nextNode = currentNode->getNext();
delete currentNode;
currentNode = nextNode;
}
return 0;
}
bool deleteAcc(const string name1)
{
Node* currentNode = head;
Node* previousNode = NULL;
while (currentNode != NULL){
if (currentNode->getData().getName() == name1) {
if (previousNode == NULL) {
// The node to be deleted is the head node
head = currentNode->getNext();
}
else {
// The node to be deleted is in the middle of the list
previousNode->setNext(currentNode->getNext());
}
delete currentNode;
return true;
}
// Update the previous node and move to the next node
previousNode = currentNode;
currentNode = currentNode->getNext();
}
// The account was not found in the list
return false;
}
The problem is that head inside the deleteAcc(name) function is outside of the scope so is it even possible to answer this question with just a single argument string inside the bool deleteAccount(string name)????
Please help. Thanks
I have tried many times to find how to solve this problem like declaring head at the top of the file before int main() like this:
Node* head = NULL;
int main(){
// functions and variables here
}
but it does not produce the desired result of showing an output.
headas a global variable? What doescurrentNode->getData()return, and is it printable?