So I'm trying to solve the Leetcode problem (#21) of merging two sorted lists, however I'm trying to do it using the standard LinkedList class in Java (the Leetcode problem uses a custom 'ListNode' class. Here's an elegant solution using the ListNode class:
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;
}
Which I understand just fine, however if I'm using the LinkedList class, what would I use in place of l1.val or l2.val? It seems LinkedList doesn't have a function for retrieving the current node value, but surely there's a way to do this? It seems like it would be very standard for a List.
l1.get(0)?