TAAFT
Free mode
100% free
Freemium
Free Trial
Create tool

Ngong David Pach

@ngongdavidpach Tasks: 54
🛠️ 1 tool 🙏 5 karma
Beginner
Joined: November 2024

Ngong David Pach's tools

  • Trust ai
    AI-powered C++ coding companion
    Open
    28
    2
    5
    Released 11mo ago
    100% Free
    ```cpp #include <iostream> // Node class for the linked list class Node { public: int data; Node* next; Node(int value) : data(value), next(nullptr) {} }; // LinkedList class class LinkedList { private: Node* head; public: LinkedList() : head(nullptr) {} // Insert a new node at the beginning of the list void insertFront(int value) { Node* newNode = new Node(value); newNode->next = head; head = newNode; } // Insert a new node at the end of the list void insertBack(int value) { Node* newNode = new Node(value); if (head == nullptr) { head = newNode; return; } Node* current = head; while (current->next != nullptr) { current = current->next; } current->next = newNode; } // Delete the first occurrence of a value in the list void remove(int value) { if (head == nullptr) return; if (head->data == value) { Node* temp = head; head = head->next; delete temp; return; } Node* current = head; while (current->next != nullptr && current->next->data != value) { current = current->next; } if (current->next != nullptr) { Node* temp = current->next; current->next = current->next->next; delete temp; } } // Display the contents of the list void display() { Node* current = head; while (current != nullptr) { std::cout << current->data << " -> "; current = current->next; } std::cout << "nullptr" << std::endl; } // Destructor to free allocated memory ~LinkedList() { Node* current = head; while (current != nullptr) { Node* temp = current; current = current->next; delete temp; } } }; int main() { LinkedList list; list.insertBack(10); list.insertBack(20); list.insertFront(5); list.insertBack(30); std::cout << "Initial list: "; list.display(); list.remove(20); std::cout << "After removing 20: "; list.display(); return 0; } ``` This code implements a basic singly linked list in C++. It includes the following features: 1. A `Node` class to represent each element in the list. 2. A `LinkedList` class that manages the list operations. 3. Methods for inserting nodes at the front and back of the list. 4. A method for removing a node with a specific value. 5. A method to display the contents of the list. 6. A destructor to free allocated memory when the list is destroyed. The `main()` function demonstrates how to use the LinkedList class by creating a list, inserting elements, removing an element, and displaying the list contents.
0 AIs selected
Clear selection
#
Name
Task