Middle Node of Linked List Java Solution

. 🚀 Day 27/40 – DSA Challenge 📌 LeetCode Problem – Middle of the Linked List 📝 Problem Statement Given the head of a singly linked list, return the middle node of the linked list. 👉 If there are two middle nodes, return the second middle node. 📌 Example Input: 1 → 2 → 3 → 4 → 5 Output: 3 📌 Even Case Input: 1 → 2 → 3 → 4 → 5 → 6 Output: 4 💡 My Approach (Counting Method) Instead of using two pointers, I used a two-step approach: 👉 First count total nodes 👉 Then move to the middle 🚀 Algorithm 1️⃣ Traverse the list and count nodes 2️⃣ Calculate middle index: mid = count / 2 3️⃣ Traverse again till mid position 4️⃣ Return that node ✅ Java Code class Solution { public ListNode middleNode(ListNode head) { int count = 0; ListNode temp = head; // Step 1: Count nodes while (temp != null) { count++; temp = temp.next; } // Step 2: Find middle index int mid = count / 2; // Step 3: Traverse to middle temp = head; for (int i = 0; i < mid; i++) { temp = temp.next; } return temp; } } ⏱ Complexity Time Complexity: O(n) (two traversals) Space Complexity: O(1) 📚 Key Learnings – Day 27 ✔ Problems can have multiple valid approaches ✔ Counting method is simple and intuitive ✔ Always think about optimizing further ✔ Same problem can be solved in one pass using fast & slow pointers Simple idea. Clear logic. Solid understanding. Day 27 completed. Consistency continues 💪🔥 #180DaysOfCode #DSA #Java #InterviewPreparation #ProblemSolving #CodingJourney #LinkedList #LeetCode

  • graphical user interface, text, application

To view or add a comment, sign in

Explore content categories