```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.