A linked list is a linear data structure that consists of a sequence of elements, where each element points to the next element in the list. In simple terms, each element of a linked list contains two fields: the actual data and a reference (or a link) to the next node.
The diagram below illustrates a simple linked list with three nodes:
1 first second third
2+-------+ +-------+ +-------+
3| data | | data | | data |
4| next ------> next ------> NULL |
5+-------+ +-------+ +-------+
In the code snippet provided, we define a Node
class that represents a single node in the linked list. Each Node
object contains an int
field data
to store the actual data and a pointer next
to refer to the next node.
To create a linked list, we create three Node
objects named first
, second
, and third
. We assign the data values to each node and establish the connections between them by setting the next
pointers. Finally, we print the contents of the linked list using the printLinkedList
function.
Feel free to modify the code and experiment with different data values and linkages. Remember to always deallocate the memory dynamically allocated for the nodes using the delete
keyword to prevent memory leaks.
xxxxxxxxxx
}
using namespace std;
// Node class
class Node {
public:
int data;
Node* next;
};
// Function to print a linked list
void printLinkedList(Node* head) {
Node* temp = head;
while (temp != nullptr) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main() {
// Create the nodes
Node* first = new Node();
Node* second = new Node();
Node* third = new Node();
// Assign data to the nodes
first->data = 1;
second->data = 2;