【发布时间】:2021-12-31 00:21:20
【问题描述】:
所以我试图解决合并两个排序列表的 Leetcode 问题(#21),但是我试图使用 Java 中的标准 LinkedList 类来解决这个问题(Leetcode 问题使用自定义的“ListNode”类。这是一个使用 ListNode 类的优雅解决方案:
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode tail = head;
while(l1 != null && l2 != null) {
if (l1.val <= l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
if (l1 != null) {
tail.next = l1;
} else if (l2 != null) {
tail.next = l2;
}
return head.next;
}
我理解得很好,但是如果我使用 LinkedList 类,我会用什么来代替 l1.val 或 l2.val? LinkedList 似乎没有检索当前节点值的功能,但肯定有办法做到这一点吗?看起来这对于 List 来说是非常标准的。
【问题讨论】:
标签: java list merge linked-list singly-linked-list