算法
-
线性表
// 创建一个数组 const array = new Array(); // for循环遍历 const len = array.length; for(let i = 0; i < len; i++){ console.log(array[i],i); } // forEach array.forEach((item,index)=>{ console.log(item,idnex) }); // map array.map((item,index)=>{ console.log(item,index); return item++; }) // 二维数组 const len = array.length; for(let i = 0; i < len; i++){ array[i] = []; } // 遍历二维数组 const outerLen = array.length; for(let i = 0; i < outerLen; i++){ const innerLen = array[i].length; for(let j = 0; j < innerLen; j++){ console.log(array[i][j],i,j); } }
// 数组方法 // 1. unshift 方法-添加元素到数组的头部 const arr = [1,2] arr.unshift(0) // [0,1,2] // 2. push 方法-添加元素到数组的尾部 const arr = [1,2] arr.push(3) // [1,2,3] // 3. splice 方法-添加元素到数组的任何位置 const arr = [1,2] arr.splice(1,0,3) // [1,3,2] // 4. shift 方法-删除数组头部的元素 const arr = [1,2,3] arr.shift() // [2,3] // 5. pop 方法-删除数组尾部的元素 const arr = [1,2,3] arr.pop() // [1,2] // 6. splice 方法-删除数组任意位置的元素 const arr = [1,2] arr.splice(1,1) // [1]
-
链表
// 定义链表 function ListNode(val){ this.val = val; this.next = null; } // new一个链表节点,并在后面追加一个节点 const node = new ListNode(1); node.next = new ListNode(2); ------------------------------------ [ 1 | next ] --> [ 2 | next ] [ 3 | next ] // 添加链表 在1⃣️节点和2⃣️节点中间添加3⃣️节点 const node3 = new ListNode(3); node3.next = node1.next; node1.next = node3; // 删除链表 删除刚才增加的3⃣️节点 node1.next = node3.next; // 总结:没有2⃣️节点什么事情,只需要找到目标节点的前驱节点就完事了。 -------------------------------------- // 遍历链表 let node = head; while(node){ node = node.next; }
-
树
// 定义树 function TreeNode(val){ this.val = val; this.left = this.right = null; } // 创建树节点 const node = new TreeNode(1);