Merging Two Sorted Linked Lists Using Iterative Method in Python
Problem Explanation You are given two sorted linked lists list1 and list2. Your task is to merge them into a single sorted linked list. The new list should be created by reusing the existing nodes....

Source: DEV Community
Problem Explanation You are given two sorted linked lists list1 and list2. Your task is to merge them into a single sorted linked list. The new list should be created by reusing the existing nodes. Example: Input: list1 = [1,2,4], list2 = [1,3,4] Output: [1,1,2,3,4,4] Input: list1 = [], list2 = [] Output: [] Method Used: Iterative Approach (Two Pointer Technique) Idea Compare nodes from both lists Pick the smaller one Move forward Repeat until one list ends Why This Method? Time complexity: O(n + m) Space complexity: O(1) Efficient and easy to implement No extra memory required Python Code with Explanation class Solution: def mergeTwoLists(self, list1, list2): Defines the function. dummy = ListNode(0) Create a dummy node to simplify merging. tail = dummy tail will build the merged list. while list1 and list2: Loop until one list becomes empty. if list1.val < list2.val: Compare values of both lists. tail.next = list1 list1 = list1.next Attach smaller node from list1. else: tail.next