Java: Merge two given sorted lists
Java Basic: Exercise-143 with Solution
Write a Java program to merge the two sorted lists.
Sample Solution:
Java Code:
public class Solution {
public static void main(String[] args) {
ListNode list1 = new ListNode(1);
list1.next = new ListNode(3);
list1.next.next = new ListNode(7);
list1.next.next.next = new ListNode(9);
list1.next.next.next.next = new ListNode(13);
ListNode list2 = new ListNode(2);
list2.next = new ListNode(40);
ListNode head = mergeTwoLists(list1, list2);
System.out.print("Merge Two Sorted ListsT:\n");
while (head != null) {
System.out.print(head.val + " ");
head = head.next;
}
}
public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode head = new ListNode(0);
ListNode mlist = head;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
mlist.next = new ListNode(list1.val);
mlist = mlist.next;
list1 = list1.next;
} else {
mlist.next = new ListNode(list2.val);
mlist = mlist.next;
list2 = list2.next;
}
}
while (list1 != null) {
mlist.next = new ListNode(list1.val);
mlist = mlist.next;
list1 = list1.next;
}
while (list2 != null) {
mlist.next = new ListNode(list2.val);
mlist = mlist.next;
list2 = list2.next;
}
head = head.next;
return head;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
Sample Output:
Merge Two Sorted ListsT: 1 2 3 7 9 13 40
Flowchart:

Java Code Editor:
Company: Microsoft Apple LinkedIn Amazon
Contribute your code and comments through Disqus.
Previous: Write a Java program to check if two given strings are anagrams or not.
Next: Write a Java program to remove all occurrences of a specified value in a given array of integers and return the new length of the array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How do I remove repeated elements from ArrayList?
If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:
Set<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set);
Of course, this destroys the ordering of the elements in the ArrayList.
Ref: https://bit.ly/3bYIjNC
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook