0
0
DSA Pythonprogramming~30 mins

Find Middle Element of Linked List in DSA Python - Build from Scratch

Choose your learning style9 modes available
Find Middle Element of Linked List
📖 Scenario: Imagine you have a line of people waiting for a bus. You want to find the person standing exactly in the middle of the line.We will represent this line as a linked list, where each person is a node connected to the next.
🎯 Goal: Build a simple linked list with 5 nodes and find the middle node's value using a step-by-step approach.
📋 What You'll Learn
Create a linked list with exactly 5 nodes with values 10, 20, 30, 40, 50 in that order
Create a variable called slow and set it to the head of the linked list
Use a loop to move slow to the middle node by moving two pointers: slow moves one step, fast moves two steps
Print the value of the middle node stored in slow.data
💡 Why This Matters
🌍 Real World
Finding the middle element is useful in many real-world problems like splitting data, balancing tasks, or finding median values.
💼 Career
Understanding linked lists and pointer techniques is important for software engineering roles, especially those involving data structures and algorithms.
Progress0 / 4 steps
1
Create the linked list with 5 nodes
Create a class called Node with an __init__ method that takes data and sets self.data and self.next. Then create 5 nodes with values 10, 20, 30, 40, 50 and link them in order. Finally, create a variable called head that points to the first node.
DSA Python
Hint

Start by defining the Node class with data and next attributes. Then create each node and link them by setting the next attribute.

2
Set up pointers to find the middle
Create two variables called slow and fast and set both to head. These will help us find the middle node.
DSA Python
Hint

Both slow and fast start at the beginning of the list.

3
Move pointers to find the middle node
Use a while loop that continues as long as fast and fast.next are not None. Inside the loop, move slow one step forward (slow = slow.next) and fast two steps forward (fast = fast.next.next).
DSA Python
Hint

Move slow one step and fast two steps in each loop until fast reaches the end.

4
Print the middle node's value
Print the value of the middle node by writing print(slow.data).
DSA Python
Hint

The middle node's value is stored in slow.data. Print it to see the result.