#9 Daily Problems -MergeTwoLinkedLists

Arun Pandian M
2 min readJul 27, 2020

--

Hi guys today is my 9th day of coding practice and solving one problem per day.

Problem:

Note: Your solution should have O(l1.length + l2.length) time complexity, since this is what you will be asked to accomplish in an interview.

Given two singly linked lists sorted in non-decreasing order, your task is to merge them. In other words, return a singly linked list, also sorted in non-decreasing order, that contains the elements from both original lists.

Example

  • For l1 = [1, 2, 3] and l2 = [4, 5, 6], the output should be
    mergeTwoLinkedLists(l1, l2) = [1, 2, 3, 4, 5, 6];
  • For l1 = [1, 1, 2, 4] and l2 = [0, 3, 5], the output should be
    mergeTwoLinkedLists(l1, l2) = [0, 1, 1, 2, 3, 4, 5].

Input/Output

  • [execution time limit] 3 seconds (java)
  • [input] linkedlist.integer l1
  • A singly linked list of integers.
  • Guaranteed constraints:
    0 ≤ list size ≤ 104,
    -109 ≤ element value ≤ 109.
  • [input] linkedlist.integer l2
  • A singly linked list of integers.
  • Guaranteed constraints:
    0 ≤ list size ≤ 104,
    -109 ≤ element value ≤ 109.
  • [output] linkedlist.integer
  • A list that contains elements from both l1 and l2, sorted in non-decreasing order.

My Solution:

// Singly-linked lists are already defined with this interface:// class ListNode<T> {//   ListNode(T x) {//     value = x;//   }//   T value;//   ListNode<T> next;// }//ListNode<Integer> mergeTwoLinkedLists(ListNode<Integer> l1, ListNode<Integer> l2){ListNode temp=l1,currentNode,nextNode;int tempValue;if(l1 ==null && l2 ==null){return   null;}else {if(temp!=null){while(temp.next!=null){temp=temp.next;}}else{if(temp==null)l1=l2;elsetemp=l2;}if(temp!=null)temp.next = l2;currentNode=l1;while(currentNode!=null){nextNode=currentNode.next;while(nextNode!=null){if((Integer)currentNode.value > (Integer)nextNode.value){tempValue=(Integer)currentNode.value;currentNode.value=nextNode.value;nextNode.value=tempValue;}nextNode=nextNode.next;}currentNode=currentNode.next;}}return l1;}

Hey guys please see my solution help me to improve myself. Lets meet tomorrow with another problem solving things.

Happy coding!

Buy me a coffee?
If you like this article, you can buy me a coffee. Thanks!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Arun Pandian M
Arun Pandian M

Written by Arun Pandian M

Senior Android developer at FundsIndia, A time investor to learn new things about Programming. Currently in a relationship with Green Bug(Android).

No responses yet

Write a response