how to traverse a linked list in c++
To traverse a linked list in C++, you can use a loop to iterate through each node in the list. Here's an example code snippet that demonstrates the process:
struct Node {
int data;
Node* next;
};
void traverseLinkedList(Node* head) {
Node* current = head;
while (current != nullptr) {
// Access the current node's data
int value = current->data;
// Do something with the value (e.g., print it)
cout << value << " ";
// Move to the next node
current = current->next;
}
}
Explanation for each step:
Define a struct named
Node
to represent each node in the linked list. It contains two members:data
to store the value of the node, andnext
to store a pointer to the next node in the list.Declare a function named
traverseLinkedList
that takes a pointer to the head of the linked list as a parameter.Inside the
traverseLinkedList
function, declare a pointer variablecurrent
and initialize it with the address of the head node. This pointer will be used to traverse the linked list.Start a
while
loop that continues until thecurrent
pointer reaches the end of the list (i.e.,nullptr
).Inside the loop, access the
data
member of the current node using the->
operator and assign it to a variable namedvalue
. This allows you to access the value stored in the current node.Perform any desired operations on the value (e.g., print it, process it, etc.). In the example code, the value is printed using
cout
.Update the
current
pointer to point to the next node in the list by assigning the value ofcurrent->next
tocurrent
. This moves the pointer to the next node in the list.Repeat steps 5-7 until the end of the list is reached.
By following these steps, you can traverse a linked list in C++ and perform operations on each node as needed.