"Java LeetCode Challenge: Merging Sorted Linked Lists"

🚀 Day 42 of 50 – Java LeetCode Challenge Today’s challenge was "21. Merge Two Sorted Lists" — a classic linked list problem that enhances your understanding of pointer manipulation and list traversal. The task focuses on merging two sorted linked lists into one sorted list efficiently. ⏱ Today’s Task – Merge Two Sorted Lists 📝 Problem Statement: You are given the heads of two sorted linked lists list1 and list2. Merge the two lists into one sorted list. The new list should be made by splicing together the nodes of the first two lists. Return the head of the merged linked list. 🔧 Constraints: 1️⃣ The number of nodes in both lists is in the range [0, 50] 2️⃣ -100 ≤ Node.val ≤ 100 3️⃣ Both list1 and list2 are sorted in non-decreasing order 🧪 Examples: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] ✅ Input: list1 = [], list2 = [] Output: [] ✅ Input: list1 = [], list2 = [0] Output: [0] ✅ 💻 My Java Solution: class Solution {   public ListNode mergeTwoLists(ListNode list1, ListNode list2) {     // Create a dummy node to act as the head of the new merged list     ListNode dummy = new ListNode(-1);     ListNode current = dummy;     // Traverse both lists while both have nodes     while (list1 != null && list2 != null) {       if (list1.val <= list2.val) {         current.next = list1;         list1 = list1.next;       } else {         current.next = list2;         list2 = list2.next;       }       current = current.next; // move forward     }     // If one list is exhausted, connect the remaining nodes of the other list     if (list1 != null) {       current.next = list1;     } else {       current.next = list2;     }     // Return the merged list starting after the dummy node     return dummy.next;   } } 🔍 Takeaways: ✅ Efficiently handles merging using a dummy node ✅ Ensures a single pass O(n + m) time complexity ✅ Demonstrates pointer manipulation and linked list traversal 💡 Core Concepts: Linked List traversal Pointer management Dummy head node usage Iterative merging 🎯 Day 42 completed — 8 more to go! 🚀 #Java #50DaysOfCode #LeetCode #ProblemSolving #LinkedList #Day42 #JavaProgramming #CodeNewbie #LearnInPublic

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories