题解 | #合并两群能量值#
合并两群能量值
https://www.nowcoder.com/practice/d728938f66ac44b5923d4f2e185667ec
考察链表合并操作。
因为已经有序,所以直接使用归并排序算法应用到链表上即可。
完整的Java代码如下所示
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) { // write code here ListNode head = new ListNode(0); ListNode result = head; while (l1 != null && l2 != null) { if (l1.val > l2.val) { head.next = new ListNode(l1.val); l1 = l1.next; } else { head.next = new ListNode(l2.val); l2 = l2.next; } head = head.next; } if (l2 != null) { head.next = l2; } else { head.next = l1; } return result.next; } }