0
0
DSA Pythonprogramming~30 mins

Get Length of Linked List in DSA Python - Build from Scratch

Choose your learning style9 modes available
Get Length of Linked List
📖 Scenario: Imagine you have a chain of boxes connected one after another. Each box holds a number and points to the next box. This is like a linked list.You want to find out how many boxes are in the chain.
🎯 Goal: Build a simple linked list with three boxes (nodes) and write code to count how many boxes are in the chain.
📋 What You'll Learn
Create a linked list with exactly three nodes containing values 10, 20, and 30
Create a variable to count the number of nodes
Use a loop to go through each node in the linked list
Print the total count of nodes
💡 Why This Matters
🌍 Real World
Linked lists are used in many software systems to store data where the size can change dynamically, like playlists, undo history, or navigation paths.
💼 Career
Understanding linked lists and how to traverse them is a fundamental skill for software developers, especially when working with low-level data structures or preparing for coding interviews.
Progress0 / 4 steps
1
Create a linked list with three nodes
Create a class called Node with an __init__ method that takes data and sets self.data and self.next to None. Then create three nodes called node1, node2, and node3 with data values 10, 20, and 30 respectively. Link node1.next to node2 and node2.next to node3. Finally, create a variable called head that points to node1.
DSA Python
Hint

Think of each node as a box holding a number and a pointer to the next box.

2
Create a counter variable
Create a variable called count and set it to 0. This will keep track of how many nodes we have counted.
DSA Python
Hint

This variable will increase as we visit each node.

3
Traverse the linked list and count nodes
Use a current variable to start at head. Use a while loop that runs as long as current is not None. Inside the loop, increase count by 1 and move current to current.next.
DSA Python
Hint

Think of walking through the chain, one box at a time, counting each box.

4
Print the length of the linked list
Write a print statement to display the value of count.
DSA Python
Hint

The output should be the number of nodes in the linked list.