数据结构复习篇之链表

101 阅读1分钟

一、单项链表

// 单向链表
class ListNode {
    constructor (val) {
        this.value = val;
        this.next = null;
    }
}

class List {
    constructor () {
        this.head = null;
        this.length = 0;
    }

    static createListNode (val) {
        return new ListNode(val);
    }

    insert (node) {
        node.next = this.head;
        this.head = node;
        this.length++;
    }

    find (key) {
        let node = this.head;
        while (node !== null && node.value !== key) {
            node = node.next;
        }
        return node;
    }

    delete (node) {
        if (this.length === 0) {
            return false;
        }

        if (node === this.head) {
            this.head = node.next;
            this.length--;
            return true;
        }

        let preNode = this.head;
        while (preNode.next !== node) {
            preNode = preNode.next;
        }
        preNode.next = node.next;
        this.length--;
    }
}

二、双向链表

class ListNode {
    constructor (val) {
        this.value = val;
        this.next = null;
        this.prev = null;
    }
}

class List {
    constructor () {
        this.head = null;
        this.length = 0;
    }

    static createListNode (val) {
        return new ListNode(val);
    }

    insert (node) {
        node.prev = null;
        node.next = this.head;
        if (this.head) {
            this.head.prev = node;
        }
        this.head = node;
        this.length++;
    }

    find (key) {
        let node = this.head;
        while (node !== null && node.value !== key) {
            node = node.next;
        }
        return node;
    }

    delete (node) {
        if (this.length === 0) {
            return false;
        }

        let nextNode = node.next;
        let preNode = node.prev;

        if (node === this.head) {
            if (nextNode) {
                nextNode.prev = null;
            }
            this.head = nextNode;
            this.length--;
            return true;
        }

        if (nextNode) {
            nextNode.prev = preNode;
        }
        preNode.next = nextNode;
        this.length--;
        return true;
    }
}

三、给定一个链表,判断链表中是否有环

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

如果链表中存在环,则返回 true 。 否则,返回 false

链接:leetcode-cn.com/problems/li…

let hasCycle = function(head) {
    if (head === null || head.next === null) {
        return false
    }
    let slowPos = head.next;
    let fastPos = head.next.next;
    while (slowPos !== fastPos) {
        if (!slowPos || !slowPos.next || !fastPos || !fastPos.next) {
            return false;
        }
        slowPos = slowPos.next;
        fastPos = fastPos.next.next;
    }
    return true;
};