链表

2020-05-24  本文已影响0人  skoll
class Node{
    constructor(el){
        this.el=el
        this.next=null
        this.pre=null
    }
}

class Llist{
    constructor(){
        this.head=new Node('head')
        this.head.pre=null
    }
    find(el){
        var currentNode=this.head
        while(currentNode.el!=el){
            currentNode=currentNode.next
        }
        return currentNode
    }
    findPrevious(item){
        var current=this.find(item)
       return current.pre
    }
    insert(newEl,item){
        var newNode=new Node(newEl)
        var current=this.find(item)

        newNode.next=current.next
        current.next=newNode
        newNode.pre=current
    }
    remove(item){
        var current=this.find(item)
        if(current.el=='head')return
        if(current.next==null){
            // 后面没有东西
            current.pre.next=null
        }else{
            current.pre.next=current.next
            current.next.pre=current.pre

            current.next=null
            current.pre=null
        }
    }
    display(){
        var current=this.head
        while(current.next!=null){
            current=current.next
            console.log(current)
        }
    }
    displayReverse(){
        let current=this.findLast()
        while(current.pre!=null){
            console.log(current)
            current=current.pre
        }
    }
    findLast(){
        // 寻找最后一个节点
        var current=this.head
        while(current.next!=null){
            current=current.next
        }
        return current
    }
}

var cities = new Llist();
cities.insert("Conway", "head");
cities.insert("Russellville", "Conway");
cities.insert("Alma", "Russellville");
// cities.display()//Conway  Russellville  Alma
// cities.remove("Russellville")
// cities.display();//Russellville  Alma
// console.log(cities.findLast())
cities.displayReverse()

// 循环列表
// 新添加的元素,last=head.pre
上一篇 下一篇

猜你喜欢

热点阅读