实现一个单向链表

45 阅读1分钟

实现起来比较简单,如下demo

function  ListNode(key) {
   this.key = key
   this.next = null
}


class LinkedList {

    constructor() {
        this.head = null
    }

    insert(node) {

        if ( this.head !== null ) {
            node.next  = this.head
        }

        this.head = node


    }
    find(node) {
        
        let p = this.head

        while ( p && p !== node ) {
            p = p.next
        }

        return p || null;
    }

}

let list = new LinkedList()

const node1 = new ListNode('00')
const node2 = new ListNode('kk')
const node3 = new ListNode('bzg')

list.insert(node1)
list.insert(node2)
list.insert(node3)

// 返回{ key: 00, next: null }
console.log(node1)
// 找不到返回null
console.log(list.find())