前端算法学习(一)-------- 线性数据结构

数组

特性:

1.存储在物理空间上连续的

2.底层的数组长度是不可变的,js中改变数组长度会很消耗性能

3.数组的变量,指向了数组第一个元素的位置(内存空间的地址)

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

缺点:

1.因为空间必须得是连续的,所以如果数组比较大,当系统的空间碎片比较多的时候,容易存不下

2.因为数组的长度是固定的,所以数组的内容难以添加和删除。

注意:

数组 a = [1,2,3,4]中,a[0]、a[1]、a[2]方括号表示存储地址的偏移,通过偏移查询数据性能最好。

var a = [1,2,3,4]; // 存储的数据长度固定使用这种
var b = new Array(10); // 存储的数据长度不固定,推荐使用这种

链表

特性:

1.空间上不是连续的

2.每存放一个值,都要多开销一个引用空间

优点:

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

2.链表的添加和删除非常的容易

缺点:

1.查询速度慢(查询某个位置)

2.链表每一个节点都需要创建一个纸箱next的引用,浪费一些空间,当节点内数据越多的时候,这部分多开销的内存影响越少

    function Node(value) {
        this.value = value;
        this.next = null;
    }
    var a = new Node(1);
    var b = new Node(2);
    var c = new Node(3);
    a.next = b;
    b.next = c;

非递归遍历

   // 数组遍历
    var arr = [1, 2, 3, 4];

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

    iterator(arr);

    // 链表的遍历
    function Node(value) {
        this.value = value;
        this.next = null;
    }

    var a = new Node(1);
    var b = new Node(2);
    var c = new Node(3);
    var d = new Node(4);
    a.next = b;
    b.next = c;
    c.next = d;

    function iterator2(head) {
        var temp = head;
        while (true) {
            if (temp != null) {
                console.log(temp.value);
            } else {
                break;
            }
            temp = temp.next;
        }
    }

    iterator2(a);

递归遍历

// 数组遍历
var arr = [1, 2, 3, 4];

function iterator(arr, i) {
    if (arr == null || arr.length <= i) return;
    console.log(arr[i]);
    iterator(arr, i + 1);
}

iterator(arr, 0);

// 链表的遍历
function Node(value) {
    this.value = value;
    this.next = null;
}

var a = new Node(1);
var b = new Node(2);
var c = new Node(3);
var d = new Node(4);
a.next = b;
b.next = c;
c.next = d;

function iterator2(head) {
    if (head == null) return;
    console.log(head.value);
    iterator2(head.next);
}

iterator2(a);

链表的逆置

// 链表的逆置
function Node(value) {
    this.value = value;
    this.next = null;
}

var a = new Node(1);
var b = new Node(2);
var c = new Node(3);
var d = new Node(4);
a.next = b;
b.next = c;
c.next = d;

function reverse(head) {
    if (head.next.next == null) {
        head.next.next = head;
        return head.next;
    } else {
        var result = reverse(head.next);
        head.next.next = head;
        head.next = null;
        return result;
    }
}

function iterator2(head) {
    if (head == null) return;
    console.log(head.value);
    iterator2(head.next);
}

var newNode = reverse(a);

iterator2(newNode);

双向链表

// 链表的逆置
function Node(value) {
    this.value = value;
    this.next = null;
    this.prev = null;
}

var a = new Node(1);
var b = new Node(2);
var c = new Node(3);
var d = new Node(4);

a.next = b;
b.prev = a;
b.next = c;
c.prev = b;
c.next = d;
d.prev = c;




原创文章 28 获赞 52 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq1123642601/article/details/104455467
今日推荐