struct Node {
int data; // The value stored in the node
Node* next; // Pointer to the next node
};
// Linked list class
class LinkedList {
private:
Node* head; // Pointer to the head (first node) of the list
public:
// Constructor
LinkedList() {
head = nullptr;
}
// Insert a node at the end of the list
void insert(int value) {
Node* newNode = new Node(); // Create a new node
newNode->data = value;
newNode->next = nullptr;
if (head == nullptr) { // If the list is empty, set head to the new node
head = newNode;
} else {
Node* temp = head;
while (temp->next != nullptr) { // Traverse to the last node
temp = temp->next;
}
temp->next = newNode; // Link the last node to the new node
}
}
// Delete a node with a specific value
void deleteNode(int value) {
if (head == nullptr) return; // If the list is empty, return
if (head->data == value) { // If the head node is the one to be deleted
Node* temp = head;
head = head->next;
delete temp;
return;
}
Node* temp = head;
while (temp->next != nullptr && temp->next->data != value) {
temp = temp->next; // Traverse to find the node to be deleted
}
if (temp->next == nullptr) return; // Node not found
Node* nodeToDelete = temp->next;
temp->next = temp->next->next;
delete nodeToDelete;
}
// Display all nodes in the list
void display() {
Node* temp = head;
while (temp != nullptr) {
Serial.print(temp->data);
Serial.print(" -> ");
temp = temp->next;
}
Serial.println("null");
}
};
LinkedList myList; // Create an instance of the linked list
void setup() {
Serial.begin(9600);
// Insert some values
myList.insert(10);
myList.insert(20);
myList.insert(30);
myList.insert(40);
Serial.println("Linked List:");
myList.display(); // Display the list
// Delete a node
Serial.println("After deleting 20:");
myList.deleteNode(20);
myList.display(); // Display the list after deletion
}
void loop() {
// Nothing to do in the loop
}