【重学算法】面试必备/考试必备

这篇博客深入探讨了数据结构的基础,包括线性表的遍历、操作(如unshift、push、splice等)以及链表的插入、删除。此外,还介绍了链表中如何添加和删除节点,以及如何遍历链表。进一步,文章讨论了树的定义及创建树节点的方法。这些内容对于理解计算机科学中的基本数据结构至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法

  1. 线性表

    // 创建一个数组
    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] 
    
  2. 链表

    // 定义链表
    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;
    }
    
  3. // 定义树
    function TreeNode(val){
      this.val = val;
      this.left = this.right = null;
    }
    
    // 创建树节点
    const node = new TreeNode(1);
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ReactSpring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值