title: give two sorted single linked list, merge two single linked list, return the result after merging;
Problem solving Ideas:
The solution is still very simple, but the following points need to be noted:
1. Returns NULL if all two linked lists are empty;
2. If the list 1 is empty, the head node of the linked list 2 is returned, whereas if the list 2 is empty, the head node of the linked list 1 is returned;
3. Two linked lists are not empty:
Compare the value of the head node of the two list, which is small, which is the head node of the new linked list;
example:l1:1->3->5; L2:2->4->6->7;: head = l1, at which point head.next = L1.next or L2
The code is as Follows:
1 /**2 * Definition for singly-linked List.3 * public class ListNode {4 * int val;5 * ListNode next;6 * ListNode (int x) {val = x;}7 * }8 */9 public classSolution {Ten publiclistnode mergetwolists (listnode l1, listnode l2) { one if(L1 = =NULL&& L2 = =NULL) a return NULL; - if(L1 = =NULL) - returnl2; the if(L2 = =NULL) - returnl1; -ListNode head =NULL; - if(l1.val >L2.val) + { -Head =l2; +Head.next =mergetwolists (l1, l2.next); a } at Else - { -Head =l1; -Head.next =mergetwolists (l1.next, l2); - } - returnhead; in } -}
Leetcode21--->merge two Sorted Lists (merge two sorted single-linked lists)