Bird
0
0
DSA Cprogramming~30 mins

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

Choose your learning style9 modes available
Find Middle Element of Linked List
📖 Scenario: You are working with a simple linked list that stores numbers. You want to find the middle number in the list, just like finding the middle book on a shelf.
🎯 Goal: Build a program that creates a linked list with 5 nodes, then finds and prints the middle element's value.
📋 What You'll Learn
Create a linked list with exactly 5 nodes with values 10, 20, 30, 40, 50
Use a pointer to traverse the list
Find the middle element using the slow and fast pointer technique
Print the middle element's value
💡 Why This Matters
🌍 Real World
Finding the middle element is useful in many applications like splitting data, balancing trees, or optimizing searches.
💼 Career
Understanding linked lists and pointer techniques is essential for software developers working with low-level data structures and memory management.
Progress0 / 4 steps
1
Create the linked list with 5 nodes
Create a struct called Node with an int data and a Node* called next. Then create 5 nodes named node1 to node5 with data values 10, 20, 30, 40, and 50 respectively. Link them so node1.next = &node2, node2.next = &node3, and so on, ending with node5.next = NULL. Finally, create a pointer head pointing to &node1.
DSA C
Hint

Remember to define the struct first, then create nodes with the given values, link them, and set the head pointer.

2
Create pointers for slow and fast traversal
Inside main, create two pointers called slow and fast and set both to point to head.
DSA C
Hint

Both slow and fast pointers start at the head of the list.

3
Find the middle element using slow and fast pointers
Use a while loop to move fast two steps and slow one step until fast is NULL or fast->next is NULL. This will make slow point to the middle node.
DSA C
Hint

Move slow by one node and fast by two nodes each loop until fast reaches the end.

4
Print the middle element's value
Use printf to print the data of the node pointed to by slow in the format: "Middle element: %d\n".
DSA C
Hint

Use printf("Middle element: %d\n", slow->data); to print the middle node's value.