前端小楽学算法记录(一)

79 阅读2分钟

数据结构与算法有什么关系

  • 可以容纳数据的结构称为数据结构。
  • 算法是用来对数据进行处理的方法。
  • 数据结构是静态的。
  • 算法是动态的。

线性数据结构(一维数据结构)

  • 强调 存储与顺序

数组(特性):数组定长。

  • 存储在物理空间上是连续的。

  • 底层的数组长度是不可变的。

  • 数组的变量,指向了数组第一个元素的位置,使用【】来取值表示存储地址的偏移。

  • 优点:查询性能好。指定查询某个位置。

  • 缺点:因为空间必须是连续的,所以如果数组比较大,容易存不下,就是当系统空间碎片较多的时候。 因为数组的长度是固定的,所以数组的内容难以被添加和删除。

链表:

  • 空间上是不连续的
  • 没存放一个值,都要多一个引用空间开销

优点:

-只要内存足够大,就能存的下,不用担心空间碎片的问题。

image.png 我想传递一个链表,我必须传递链表的根节点。每一个节点,都认为自己是根节点。,因为每一个节点只记录自己的数据,以及下一个数据的地址。

缺点:

  • 查询速度慢
  • 浪费一些空间
// 创建链表一个数据的节点
function(value){
 this.value = value
 this.next = null
}

线性数据结构的遍历

遍历: 将一个集合中的每一个元素进行获取并查看。

var arr = [1,2,3,4,5,6]

function bianli(arr){
 if(arr === null) return 
 for(i=0;i<arr.length;i++){
     console.log(arr[i])
 }
}

线性数据结构的递归遍历

var arr = [1,2,3,4,5,6,7,8];

function bianArr(arr){
    if(arr === null) return;
    
    for(i = 0; i < arr.length; i ++){
        console.log(arr[i]);
    }
}


function Node(value){
    this.value = value;
    this.next = null;
}

var node1 = new Node(1);
var node2 = new Node(2);
var node3 = new Node(3);
var node4 = new Node(4);
var node5 = new Node(5);

node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node5

//while 循环遍历
function bianLink(root){
    var temp = root
    while(true){
        if(temp !==null){
            console.log(temp)
        }else{
            break
        }
        temp = root.next;
    }
}

//递归循环遍历

function digui(root){
    if(root ===null) return;
    console.log(root.value)
    digui(root.next);
}

//递归遍历必须有出口

//数组递归遍历
function arrDigui(arr,i){
    if(arr === null || arr.length <= i) return;
    console.log(arr[i]);
    i++
    arrDigui(arr,i);
}

链表的逆置

function Node(value){
    this.value = value;
    this.next = null;
}

let node1 = new Node(1);
let node2 = new Node(2);
let node3 = new Node(3);
let node4 = new Node(4);
let node5 = new Node(5);

node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;

function reverseList(root){
    //首先判断我们传入的数据不为空
    if(root == null) return null;
    //我们的思路是使用递归实现逆置,最后的出口在找到倒数第二个节点
    if(root.next.next == null){
        // 找到倒数第二个节点
        root.next.next =root;
        return root.next;
    }else{
        //接受抛出的起始节点
        let result = reverseList(root.next);
        //把当前节点的下一个节点的指向指向当前节点
        root.next.next = root;
        //把当前节点的指向指向null
        root.next = null;
        // 返回起始节点
        return result;
    }
}

function bianli(root){
    if(root == null) return;
    console.log(root.value);
    bianli(root.next);
}

bianli(reverseList(node1));