Implement singly linked lists.
Implement singly linked lists.
#include <iostream>
using namespace std;
// Node class represents a single node in the linked list
class Node {
public:
int data; // Data stored in the node
Node* next; // Pointer to the next node
// Constructor
Node(int value) {
data = value;
next = nullptr;
}
};
// Linked list class represents the entire linked list
class LinkedList {
private:
Node* head; // Pointer to the head node
public:
// Constructor
LinkedList() {
head = nullptr;
}
// Destructor to free memory
~LinkedList() {
Node* current = head;
while (current != nullptr) {
Node* next = current->next;
delete current;
current = next;
}
}
// Function to insert a node at the beginning of the list
void insertAtBeginning(int value) {
Node* newNode = new Node(value);
newNode->next = head;
head = newNode;
}
// Function to insert a node at the end of the list
void insertAtEnd(int value) {
Node* newNode = new Node(value);
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// Function to display the linked list
void display() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
LinkedList list;
// Inserting elements at the beginning
list.insertAtBeginning(3);
list.insertAtBeginning(2);
list.insertAtBeginning(1);
// Displaying the list
cout << "Linked List after inserting elements at the beginning: ";
list.display();
// Inserting elements at the end
list.insertAtEnd(4);
list.insertAtEnd(5);
list.insertAtEnd(6);
// Displaying the list
cout << "Linked List after inserting elements at the end: ";
list.display();
return 0;
}
Comments
Post a Comment