https://leetcode.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
1 public class Solution { 2 public static ListNode mergeTwoLists(ListNode l1, ListNode l2) { 3 if(l1==null){return l2;} 4 if(l2==null){return l1;} 5 ListNode head=new ListNode(0); 6 ListNode list1=l1; 7 ListNode list2=l2; 8 if(list1.val<=list2.val){head.next=l1;list1=list1.next;} 9 else{head.next=list2;list2=list2.next;} 10 ListNode list=head.next; 11 while(list1!=null&&list2!=null){ 12 if(list1.val<=list2.val){list.next=list1;list=list.next;list1=list1.next;} 13 else{list.next=list2;list=list.next;list2=list2.next;} 14 } 15 if(list1==null){list.next=list2;} 16 else if(list2==null){list.next=list1;} 17 return head.next; 18 } 19 public static class ListNode { 20 int val; 21 ListNode next; 22 23 ListNode(int x) { 24 val = x; 25 } 26 } 27 public static void main(String[]args){ 28 ListNode[]node=new ListNode[4]; 29 for(int i=0;i<node.length;i++){ 30 node[i]=new ListNode(i+2); 31 } 32 node[0].next=node[1]; 33 node[1].next=node[2]; 34 node[2].next=node[3]; 35 ListNode node1=new ListNode(0); 36 ListNode node2=new ListNode(6); 37 node1.next=node2; 38 ListNode head=mergeTwoLists(node[0],node1); 39 while(head!=null){ 40 System.out.println(head.val); 41 head=head.next; 42 } 43 } 44 }