Mental Model
Count how many nodes are in the linked list by moving from the start to the end one by one.
Analogy: Like counting people in a line by walking from the first person to the last, counting each person you pass.
head -> 1 -> 2 -> 3 -> null
head -> 1 -> 2 -> 3 -> null
head -> [curr->1] -> 2 -> 3 -> null, count=0
head -> 1 -> [curr->2] -> 3 -> null, count=1
head -> 1 -> 2 -> [curr->3] -> null, count=2
head -> 1 -> 2 -> 3 -> [curr->null], count=3
head -> 1 -> 2 -> 3 -> null, length = 3
#include <iostream> using namespace std; struct Node { int data; Node* next; Node(int val) : data(val), next(nullptr) {} }; int getLength(Node* head) { int count = 0; Node* curr = head; while (curr != nullptr) { count++; // count current node curr = curr->next; // move to next node } return count; } int main() { // Create linked list 1 -> 2 -> 3 -> null Node* head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); int length = getLength(head); cout << "Length of linked list: " << length << endl; // Clean up memory Node* curr = head; while (curr != nullptr) { Node* temp = curr; curr = curr->next; delete temp; } return 0; }
while (curr != nullptr) {count++; // count current nodecurr = curr->next; // move to next nodewhile (curr != nullptr) {while (curr != nullptr) {getLength do when given the head of a linked list?getLength counts nodes starting from the head until the end.Node* and can be initialized to NULL or nullptr.Node* head = NULL; which is correct pointer initialization syntax.struct Node {
int data;
Node* next;
};
int getLength(Node* head) {
int count = 0;
while (head != NULL) {
count++;
head = head->next;
}
return count;
}
int main() {
Node n3 = {30, NULL};
Node n2 = {20, &n3};
Node n1 = {10, &n2};
int length = getLength(&n1);
std::cout << length;
return 0;
}int getLength(Node* head) {
int count = 0;
while (head->next != NULL) {
count++;
head = head->next;
}
return count;
}head->next != NULL, so it stops before the last node.getLength function to return the length only if all node values are positive? If any node has zero or negative value, return -1.Pass the test and this pattern moves unknown