题解 | #合并两个有序链表#
合并两群能量值
https://www.nowcoder.com/practice/d728938f66ac44b5923d4f2e185667ec
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 0 1 1 1 1 1 0 0 0 * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ public ListNode mergeEnergyValues (ListNode l1, ListNode l2) { // write code here // 1. 处理特殊情况 if (l1 == null || l2 == null) return l1 == null ? l2 : l1; // 2. 开始遍历处理 ListNode newHead = new ListNode(-1); ListNode tmp = newHead; while (l1 != null && l2 != null) { if (l1.val > l2.val) { tmp.next = l1; l1 = l1.next; } else { tmp.next = l2; l2 = l2.next; } tmp = tmp.next; } // 3. 行至此处二者要么同为null,要么一个为null if (l1 != null) { tmp.next = l1; } if (l2 != null) { tmp.next = l2; } // 4. 返回 return newHead.next; } }