Data Structures and Algorithms: Length of Linked List šŸŽÆ

beginner
16 min

Data Structures and Algorithms: Length of Linked List šŸŽÆ

Welcome to our deep dive into the fascinating world of Data Structures and Algorithms! Today, we'll focus on a crucial problem - determining the length of a Linked List šŸ“. This lesson is designed to help both beginners and intermediates understand the concept from the ground up. Let's get started!

What is a Linked List? šŸ’”

A Linked List is a linear data structure, consisting of nodes that contain data and a reference (link) to the next node in the sequence. This structure is dynamic, allowing for efficient insertion and deletion of elements.

markdown
class Node: def __init__(self, data): self.data = data self.next = None

In the above code, we define a basic Node class. Each node has a data attribute (the actual value) and a next attribute (a reference to the next node).

Creating a Linked List šŸ“

Let's create a simple Linked List with some data.

markdown
head = Node(1) second = Node(2) head.next = second

In this example, we create a Linked List with two nodes: 1 and 2. We connect the second node to the first one using the next attribute.

Finding the Length of a Linked List šŸ’”

To find the length of a Linked List, we traverse the list from the head node, counting each node we encounter.

markdown
def length(head): current = head count = 0 while current is not None: count += 1 current = current.next return count

In the above code, we define a function length(head) that calculates the length of a given Linked List. We start from the head node, iteratively moving to the next node, incrementing the count for each node we visit.

Putting it all together šŸ’”

Let's create a Linked List and calculate its length.

markdown
head = Node(1) second = Node(2) third = Node(3) head.next = second second.next = third print(length(head)) # Output: 3

In this example, we create a Linked List with three nodes (1, 2, and 3) and calculate its length, which is 3.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

Which line connects the second node to the first one in the Linked List?

By the end of this lesson, you should have a solid understanding of how to create and traverse a Linked List, as well as determining its length. Happy coding! šŸš€