You are given the heads of two sorted linked lists list1 and list2.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
Solution : In Java
JAVA1/** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11class Solution { 12 public ListNode mergeTwoLists(ListNode list1, ListNode list2) { 13 ListNode ptr1=list1,ptr2=list2; 14 ListNode merged=new ListNode(0); 15 ListNode ptr=merged; 16 while(ptr1!=null && ptr2!=null){ 17 if(ptr1.val<ptr2.val){ 18 ListNode t=new ListNode(ptr1.val); 19 ptr.next=t; 20 ptr1=ptr1.next; 21 }else{ 22 ListNode t=new ListNode(ptr2.val); 23 ptr.next=t; 24 ptr2=ptr2.next; 25 } 26 ptr=ptr.next; 27 } 28 if(ptr1!=null) ptr.next=ptr1; 29 else ptr.next=ptr2; 30 return merged.next; 31 } 32}