|
@@ -0,0 +1,92 @@
|
|
|
+/*
|
|
|
+ * @Description:
|
|
|
+ * @Autor: kindring
|
|
|
+ * @Date: 2022-05-17 14:04:16
|
|
|
+ * @LastEditors: kindring
|
|
|
+ * @LastEditTime: 2022-05-17 16:09:40
|
|
|
+ * @LastDescript:
|
|
|
+ */
|
|
|
+/**
|
|
|
+ * Definition for singly-linked list.
|
|
|
+ * function ListNode(val, next) {
|
|
|
+ * this.val = (val===undefined ? 0 : val)
|
|
|
+ * this.next = (next===undefined ? null : next)
|
|
|
+ * }
|
|
|
+ */
|
|
|
+
|
|
|
+function ListNode(val, next) {
|
|
|
+ this.val = (val === undefined ? 0 : val)
|
|
|
+ this.next = (next === undefined ? null : next)
|
|
|
+}
|
|
|
+
|
|
|
+let l = ATL([1, 2, 3]);
|
|
|
+// console.log(l);
|
|
|
+/**
|
|
|
+ * 数组转链表,递归版本
|
|
|
+ */
|
|
|
+function ATL(arr, i = 1, _l) {
|
|
|
+ if (i > arr.length) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ if (!_l) {
|
|
|
+ _l = new ListNode(arr[0])
|
|
|
+ }
|
|
|
+ _l.next = ATL(arr, i + 1, new ListNode(arr[i]))
|
|
|
+ return _l
|
|
|
+}
|
|
|
+
|
|
|
+/**
|
|
|
+ * @param {ListNode} l1
|
|
|
+ * @param {ListNode} l2
|
|
|
+ * @return {ListNode}
|
|
|
+ */
|
|
|
+var addTwoNumbers = function(l1, l2) {
|
|
|
+ let prevValue = 0;
|
|
|
+ // 总返回用的表
|
|
|
+ let r = new ListNode()
|
|
|
+ let t = r;
|
|
|
+ let arr = []
|
|
|
+ // 以l1 为基准.将l1中的所有值进行添加
|
|
|
+ while (l1 || l2) {
|
|
|
+ // console.log(l1);
|
|
|
+ let v1 = l1 ? l1.val : 0,
|
|
|
+ v2 = l2 ? l2.val : 0;
|
|
|
+ let v = (v1 + v2 + prevValue) % 10;
|
|
|
+ prevValue = ~~((v1 + v2 + prevValue) / 10);
|
|
|
+ arr.push(v);
|
|
|
+ l1 = l1 ? l1.next : null;
|
|
|
+ l2 = l2 ? l2.next : null;
|
|
|
+ if (!t) {
|
|
|
+ t = new ListNode();
|
|
|
+ r.val = v;
|
|
|
+ r.next = t;
|
|
|
+ } else {
|
|
|
+ t.val = v;
|
|
|
+ if (!l1 && !l2) {
|
|
|
+ if (prevValue) {
|
|
|
+ t.next = new ListNode(prevValue);
|
|
|
+ }
|
|
|
+ return r;
|
|
|
+ }
|
|
|
+ t.next = new ListNode()
|
|
|
+ t = t.next
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return r;
|
|
|
+};
|
|
|
+let _1 = ATL([1, 2]);
|
|
|
+let x = addTwoNumbers(_1, ATL([2, 3, 4]))
|
|
|
+console.log(x);
|
|
|
+console.log(x.next);
|
|
|
+console.log(x.next.next);
|
|
|
+let n1 = ATL([9, 9, 9, 9, 9, 9, 9])
|
|
|
+let n2 = ATL([9, 9, 9, 9])
|
|
|
+let x2 = addTwoNumbers(n1, n2)
|
|
|
+console.log(x2.next.val);
|
|
|
+console.log(x2.next.next.val);
|
|
|
+console.log(x2.next.next.next.val);
|
|
|
+console.log(x2.next.next.next.next.val);
|
|
|
+console.log(x2.next.next.next.next.val);
|
|
|
+console.log(x2.next.next.next.next.next.next.val);
|
|
|
+console.log(x2.next.next.next.next.next.next.next.val);
|
|
|
+console.log(x2.next.next.next.next.next.next.next.next.val);
|