JavaScript 의 데이터 구조 링크

16894 단어 자바 script
function defaultEquals (a, b) {
  return a===b
}
class Node{
  constructor(element) { 
    this.element = element
    this.next=undefined
  }
}
class LinkedList {
  constructor(equalsFn =defaultEquals) {
    this.count = 0
    this.head=undefined
    this.equalsFn =equalsFn
  }
  //          
  push (el) {
    //      
    const node = new Node(el)
    let current
    //         null
    if (this.head == null) {
      //          
      this.head=node
    } else {
      //        
      current = this.head
      while (current.next!=null) {
        current=current.next
      }
      //                
      current.next=node
    }
    //     1
    this.count++
  }
  //         
  getElement (index) {
    if (index>=0&& index<=this.count) {
      let node = this.head
      for (let i = 0; i < index&&node!=null; i++) {
        node=node.next
      }
      return node
    }
    return undefined
  }
  //        
  removeAt (index) {
    
    //          
    if (index >= 0 && index <= this.count) {
      let current = this.head
      if (index===0) {
        this.head=current.next
      } else {
        //            
        const previous = this.getElement(index - 1)
        //      
        current = previous.next
        //                  ,      
        previous.next=current.next
      }
      this.count--
    }
    return undefined
  }
  //    
  insert(index,el){
    //      
    if(index>=0&&index<=this.count){
      //    
      const node=new Node(el)
      //    0   
      if(index===0){
        const current=this.head
        node.next = current
        this.head=node
      }else{
        //        
        const previous=this.getElement(index-1)
        const current =previous.next
        node.next=current
        previous.next=node
      }
      this.count++
      return true
    }
    return false
  }
  //    
  indexOf(el){
    let current=this.head
    for (let i = 0; i < this.count&&this.current!=null; i++) {
      if(this.equalsFn(el,current.element)){
        return i
      }
      current=current.next      
    }
    return -1
  }
  //      
  size(){
    return this.count
  }
  //      
  isEmpty(){
    return this.count()===0
  }
  //     
  getHead(){
    return this.head
  }
  //     
  toString () {
    if (this.isEmpty()) {
      return ''
    }
    let str = `${this.head.element}`
    let current=this.head.next
    for (let i = 1; i <this.size()&&current!=null; i++) {
      str += `,${current.element}`
      current=current.next
    }
    return str
  }
}

좋은 웹페이지 즐겨찾기