Approach:
Step 1 Take both linked lists
Step 2 Create dummy node
Step 3 Compare nodes of both lists
Step 4 Attach smaller node to result
Step 5 Move pointer forward
Step 6 Attach remaining nodes
Why this works???
Both lists already sorted
so comparing one by one gives sorted result
no need to sort again
Code:
class ListNode:
def init(self,val=0,next=None):
self.val=val
self.next=next
def mergeTwoLists(list1,list2):
dummy=ListNode()
current=dummy
while list1 and list2:
if list1.val<list2.val:
current.next=list1
list1=list1.next
else:
current.next=list2
list2=list2.next
current=current.next
current.next=list1 if list1 else list2
return dummy.next
Limitation:
Requires linked list understanding
not for arrays directly
Top comments (0)