Merge Two Sorted Lists - Linked List - Easy - LeetCode
💻 coding

Merge Two Sorted Lists - Linked List - Easy - LeetCode

1 min read 159 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to merge two sorted linked lists into a new sorted list by splicing their nodes.
  • 2The provided solution uses a while loop to compare nodes and build the merged list iteratively.
  • 3The time complexity of the merging process is O(m+n), while the space complexity is also O(m+n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to merge two sorted linked lists into a new sorted list by splicing their nodes."

Merge Two Sorted Lists - Linked List - Easy - LeetCode

Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * public int val;
 * public ListNode next;
 * public ListNode(int val=0, ListNode next=null) {
 * this.val = val;
 * this.next = next;
 * }
 * }
 */
public class Solution {
 public ListNode MergeTwoLists(ListNode l1, ListNode l2) {
 if(l1==null){
 return l2;
 }
 
 if(l2==null){
 return l1;
 }
 
 ListNode head=null;
 ListNode temp = null;
 while(l1!=null && l2!=null){
 if(l1.val<l2.val){
 if(head==null){
 head=l1;
 temp=head; 
 }
 else{
 temp.next=l1;
 temp=temp.next;
 }
 l1=l1.next;
 }
 else{
 if(head==null){
 head=l2;
 temp=head; 
 }
 else{
 temp.next=l2;
 temp=temp.next;
 }
 l2=l2.next;
 }
 }
 
 if(l1!=null){
 temp.next = l1;
 }
 
 if(l2!=null){
 temp.next = l2;
 }
 
 return head;
 }
}

Time Complexity: O(m+n)

Space Complexity: O(m+n) to store the result

Here m and n are the lengths of linked lists.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 30 September 2020 · 1 min read · 159 words

Part of AskGif Blog · coding

You might also like

Merge Two Sorted Lists - Linked List - Easy - LeetCode | AskGif Blog