# Merge Two Sorted Lists Leetcode Solution

## Merge Two Sorted List LeetCode Solution :

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

## Merge Two Sorted Lists LeetCode Solution :

### Constraints :

• The number of nodes in both lists is in the range [0, 50].
• -100 <= Node.val <= 100
• Both list1 and list2 are sorted in non-decreasing order.

## Approach for Merge Two Sorted Lists LeetCode Solution : :

1. We start by initializing a dummy node. This dummy node is a placeholder and simplifies the code since it allows us to handle the edge cases more easily.

2. We have two pointers, one for each input linked list (list1 and list2), initially pointing to their respective heads.

3. We iterate through both lists, comparing the values of the nodes pointed to by the two pointers.

4. At each step, we append the node with the smaller value to the merged list, and we advance the corresponding pointer to the next node in that list.

5. We repeat this process until we have iterated through both lists entirely.

6. If one of the lists becomes exhausted before the other, we simply attach the remaining part of the non-empty list to the merged list.

7. Finally, we return the head of the merged list, which is the next node after the dummy node.

### Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

## Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others