Linked List
In the world of data structures, a linked list is a linear collection of nodes, where each node contains data and a reference to the next node in the list. Unlike arrays, linked lists do not require contiguous memory locations, making them more flexible and efficient in certain scenarios.
Creating a Linked List
To create a linked list in C++, we use a struct to define the structure of a node. Each node typically contains a data element and a pointer to the next node in the list.
Here's an example of creating a linked list with three nodes:
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Creating an empty linked list
6 struct Node {
7 int data;
8 struct Node* next;
9 };
10
11 struct Node* head = NULL;
12
13 // Inserting elements into the linked list
14 struct Node* newNode = new Node;
15 newNode->data = 10;
16 newNode->next = NULL;
17 head = newNode;
18
19 newNode = new Node;
20 newNode->data = 20;
21 newNode->next = NULL;
22 head->next = newNode;
23
24 newNode = new Node;
25 newNode->data = 30;
26 newNode->next = NULL;
27 head->next->next = newNode;
28
29 // Traversing the linked list
30 struct Node* temp = head;
31 while (temp != NULL) {
32 cout << temp->data << "\n";
33 temp = temp->next;
34 }
35
36 return 0;
37}
Traversing the Linked List
To traverse a linked list, we start from the head node and follow the next pointers until we reach the end of the list. During traversal, we can access and perform operations on each node as needed.
In the example above, we traverse the linked list and print out the data value of each node.
Keep in mind that this example is simplified and only demonstrates the basic concept of a linked list. In practice, linked lists can be more complex and offer additional functionality depending on the requirements of the application.
xxxxxxxxxx
}
using namespace std;
int main() {
// Creating an empty linked list
struct Node {
int data;
struct Node* next;
};
struct Node* head = NULL;
// Inserting elements into the linked list
struct Node* newNode = new Node;
newNode->data = 10;
newNode->next = NULL;
head = newNode;
newNode = new Node;
newNode->data = 20;
newNode->next = NULL;
head->next = newNode;
newNode = new Node;
newNode->data = 30;
newNode->next = NULL;
head->next->next = newNode;
// Traversing the linked list