33. Merge ordered linked lists

Title description

Merging two ordered linked lists into a new linked list requires that the new linked list is generated by splicing the nodes of the two linked lists, and the new linked list is still in order after the merger.

 

Example 1

enter

{1},{2}

return value

{1,2}

Example 2

enter

{2},{1}

return value

{1,2}
代码实现:
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param l1 ListNode类 
     * @param l2 ListNode类 
     * @return ListNode类
     */
    public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
        ListNode tmp = new ListNode(0);
        ListNode head = tmp;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                head.next = l2;
                l2 = l2.next;
            } else {
                head.next = l1;
                l1 = l1.next;
            }
            head = head.next;
        }
        if (l1 != null) {
            head.next = l1;
        }
        if (l2 != null) {
            head.next = l2;
        }
         return tmp.next;
    }
   
}

 

Guess you like

Origin blog.csdn.net/xiao__jia__jia/article/details/113448692