public ListNode mergeTwoLists(ListNode list1, ListNode list2) { //new a head to return; ListNodehead=null; //check two heads are available to merge if(list1 == null){ return list2; } if(list2 == null){ return list1; } if(list1 == null && list2 == null){ return head; }
//build three pointers, cur for the last element in the sorted linkedlist; //cur1 for the first element in the list1; //cur2 for the first element in the list2; //we can decide the head now; ListNode cur1; ListNode cur2; if(list1.val > list2.val){ head = list2; cur1 = list1; cur2 = list2.next; } else{ head = list1; cur1 = list1.next; cur2 = list2; } ListNodecur= head;
//while loop to check which one is biger, until one of pointers of one list is null; while(cur1 != null && cur2 != null){ if(cur1.val < cur2.val){ cur.next = cur1; cur = cur.next; cur1 = cur1.next; } else{ cur.next = cur2; cur = cur.next; cur2 = cur2.next; } } //check which list pointer is null; direct use 'cur' point to the pointer which still has linkedlist left; if(cur1 != null){ cur.next = cur1; } else{ cur.next = cur2; } return head; }