题解 | #合并两群能量值#
合并两群能量值
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 { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ public ListNode mergeEnergyValues (ListNode l1, ListNode l2) { ListNode dummy = new ListNode(-1); ListNode p = dummy; while(l1 != null && l2 != null){ //比较哪个值大就那个值作为头指针 if(l1.val > l2.val){ p.next = l1; l1 = l1.next; }else{ p.next = l2; l2 = l2.next; } p = p.next; } if(l1 != null){ p.next = l1; } if(l2 != null){ p.next = l2; } return dummy.next; } }
使用dummy虚拟指针