c++ data structures linked list delete node
bool deleteNode(int); pass this method an id to delete. Return true or false to indicate success or failure. Delete the memory the node was using
The algorithm for deleting a Node to a Linked List (general case): ● Begin at the head. ● Compare the id to the current node. ● If search id > current id, stop. ● Detach the current Node ○ current->previous->next = current->next ○ current->next->previous = current->previous ● Deallocate the current Node (no need to detach it’s pointers). ● Return T/F based on successful deletion or not. Note: there are two special cases, delete the head, delete the tail. They are analogous to the add Node special cases. This is left up to the reader to discern
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "data.h"
#include <iostream> //take this out
using std::cout;
class LinkedList{
public:
LinkedList();
~LinkedList();
bool addNode(int, string);
bool deleteNode(int);
bool getNode(int, Data*);
void printList(bool = false);
int getCount();
void clearList();
bool exists(int);
private:
Node *head;
};
#endif
----------------------------------------------------------------------------
#ifndef DATA_H
#define DATA_H
#include "string"
using std::string;
struct Data {
int id;
string data;
};
struct Node {
Data data;
Node *next;
Node *prev;
};
#endif /* DATA_H */
------------------------------------------------------
bool LinkedList::deleteNode(int id){
bool success;
Node *current = head;
if(current == NULL){
success = false;
}
while(current != NULL){
if(current -> data.id == id){
current = current -> next;
current = nullptr;
delete current;
}
success = true;
}
return success;
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "data.h"
#ifndef DATA_H
#define DATA_H
#include "string"
#include <iostream> //take this out
using std::cout;
class LinkedList{
public:
LinkedList();
bool addNode(int, string);
bool deleteNode(int);
bool getNode(int, Data*);
void printList(bool = false);
int getCount();
void clearList();
bool exists(int);
private:
Node *head;
};
using std::string;
struct Data {
int id;
string data;
};
struct Node {
Data data;
Node *next;
Node *prev;
};
bool LinkedList::deleteNode(int id){
bool success;
Node *current = head;
Node *n=NULL;
if(current == NULL){
success = false;
}
while(current != NULL){
if(current -> data.id == id){
current->data = current->next->data;
n = current->next;
// Remove the link of next node
current->next = current->next->next;
// free memory
free(n);
success = true;
}
else{
current=current->next;
success=false;
}
}
return success;
Get Answers For Free
Most questions answered within 1 hours.