1. Introduction
Record a little knowledge learned by doing leetcode to see the answers...
Some application scenarios in which shallow copy implements some special functions
2. text
For example, we have a requirement as follows
{ val:0, child:null } //==> { val:0, child:{ val:1, child:{ val:2, child:{ ... } } } }
We can do that
let obj1={ val:0, child:null }, obj2=obj1, i=1 while(i<10){ obj1.child={ val:i, child:null }; obj1=obj1.child i++ } console.log("obj1:",obj1,"obj2:",obj2)//Go to the console to test obg1: {Val: 9, child: null}, obb2: {Val: 0, child: { P
So I want to extend how js solves the problem of a linked list, Implementation of js linked list
Here is the title:
Two non empty linked lists are given to represent two non negative integers. Their respective digits are stored in reverse order, and each node can only store one digit. If we add the two numbers together, we will return a new linked list to represent their sum. You can assume that neither of these numbers starts with 0 except for the number 0. Example: Input: (2 - > 4 - > 3) + (5 - > 6 - > 4) Output: 7 - > 0 - > 8 Reason: 342 + 465 = 807
How to achieve:
function ListNode(val) { this.val = val; this.next = null; } var addTwoNumbers = function(l1, l2) { if(l1 === null || l2 === null){ return l1 || l2; } var result = new ListNode(0); var cur = result;//Detail operation var p = l1; var q = l2; var carry = 0; while(p || q){ var qval; var pval; if(q){ qval = q.val; q = q.next; } else { qval = 0; } if(p){ pval = p.val; p = p.next; } else { pval = 0; } var val = qval + pval + carry; if(val > 9){ carry = 1; val %= 10; } else { carry = 0; } cur.next = new ListNode(val); cur = cur.next; } //This is a carry greater than 1, indicating that the number of digits is exceeded. For example, 99 = > 100999 = > 1000, fill in 1 at the end. if(carry !== 0){ cur.next = new ListNode(1); } return result.next; };
ok 👌 only this self-study record, if you are not careful to help, it is a great honor!