I'm trying to solve the leecode problems, I understood the first problem (two sum) and I got stuck in the second exercise of the platform, I didn't understand what .val, .next, new (ListNode) is, I believe it's a linked list that I need to study but I didn't understand everything and it seems that it is not so, can anyone help me? Could it be that what's missing is just object orientation that I still intend to learn? what I know is basic algorithms that I studied for programming logic and javascript and node base, thanks for your attention
this code is the solution to the problem, which has elements that I couldn't understand
var addTwoNumbers = function(l1, l2) {
let sum = 0;
let current = new ListNode(0);
let result = current;
while(l1 || l2) {
if(l1) {
sum += l1.val;
l1 = l1.next;
}
if(l2) {
sum += l2.val;
l2 = l2.next;
}
current.next = new ListNode(sum % 10);
current = current.next;
sum = sum > 9 ? 1 : 0;
}
if(sum) {
current.next = new ListNode(sum);
}
return result.next;
};
There is a class called ListNode which are nodes of a linked list. When you initialize a node, its along the lines of
let newNode = new ListNode(val, next=null)
//ex
let head = new ListNode(null)
let nodeOne = new ListNode(10)
let nodeTwo = new Listnode(11)
head.next = NodeOne
nodeOne.next = NodeTwo
Linked list looks like: [noData, pointer to node1] --> [10, pointer to node2] --> [11, null pointer]
val is the value of the node (the data you want to store in the node) and next is a pointer to the next node so you know what comes after it. The default value of the next parameter is always null. You can set the value of node.next to the node that comes after it so you can create a chain. When check class properties it's in the format of this.val or this.next, so to directly see the value you use do newNode.val or newNode.next to see these values.
Null pointers signify the end of a linked list.
You should probably watch a beginners linked list video.