Table of contents | |
Introduction | |
Iterative Approach | |
Recursive Approach | |
Sample Problems |
The iterative approach involves traversing the linked list from the head node to the tail node and counting the number of nodes encountered.
Code Example
#include <iostream>
struct Node {
int data;
Node* next;
};
int getLengthIterative(Node* head) {
int length = 0;
Node* current = head;
while (current != nullptr) {
length++;
current = current->next;
}
return length;
}
int main() {
// Create a sample linked list: 1 -> 2 -> 3 -> nullptr
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
int length = getLengthIterative(head);
std::cout << "Length of the linked list: " << length << std::endl;
return 0;
}
Explanation
Code Output
Length of the linked list: 3
The recursive approach involves calling a recursive function on the next node and adding 1 to the result until reaching the end of the linked list.
Code Example
#include <iostream>
struct Node {
int data;
Node* next;
};
int getLengthRecursive(Node* node) {
if (node == nullptr)
return 0;
else
return 1 + getLengthRecursive(node->next);
}
int main() {
// Create a sample linked list: 1 -> 2 -> 3 -> nullptr
Node* head = new Node{1, nullptr};
head->next = new Node{2, nullptr};
head->next->next = new Node{3, nullptr};
int length = getLengthRecursive(head);
std::cout << "Length of the linked list: " << length << std::endl;
return 0;
}
Explanation
Code Output
Length of the linked list: 3
Problem 1: Write a function to find the length of a singly linked list with a recursive approach.
int getLengthRecursive(Node* node) {
if (node == nullptr)
return 0;
else
return 1 + getLengthRecursive(node->next);
}
Problem 2: Write a function to find the length of a singly linked list with an iterative approach.
int getLengthIterative(Node* head) {
int length = 0;
Node* current = head;
while (current != nullptr) {
length++;
current = current->next;
}
return length;
}
In this article, we discussed two approaches to find the length of a linked list: iterative and recursive. We provided easy-to-understand code examples, explanations, and code outputs for each approach. By understanding these concepts, you can efficiently determine the length of a linked list in your C++ programs. Remember to choose the approach that best suits your needs and the requirements of your application.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|