#9 Daily Problems -MergeTwoLinkedLists
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]
andl2 = [4, 5, 6]
, the output should bemergeTwoLinkedLists(l1, l2) = [1, 2, 3, 4, 5, 6]
; - For
l1 = [1, 1, 2, 4]
andl2 = [0, 3, 5]
, the output should bemergeTwoLinkedLists(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
andl2
, 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!