• JS版数据结构链表


    链表代码随笔(JS)

    /** 链表节点 */
    class Node {
      el = null;
      next = null;
    
      constructor(el = null, next = null) {
        this.el = el;
        this.next = next;
      }
    }
    
    /** 链表 */
    class LinkedList {
      #dummy = null;
      #size = 0;
    
      constructor() {
        this.#dummy = new Node();
      }
    
      getSize() {
        return this.#size;
      }
    
      isEmpty() {
        return this.#size === 0;
      }
    
      insert(idx, el) {
        if (idx < 0 || idx > this.#size) {
          throw new Error('Out of bounds!');
        }
        let prev = this.#dummy;
        for (let i = 0; i < idx; i++) {
          prev = prev.next;
        }
        prev.next = new Node(el, prev.next);
        this.#size++;
      }
    
      addFirst(el) {
        this.insert(0, el);
      }
    
      addLast(el) {
        this.insert(this.#size, el);
      }
    
      get(idx) {
        if (idx < 0 || idx >= this.#size) {
          throw new Error('Out of bounds!');
        }
        let cur = this.#dummy.next;
        for (let i = 0; i < idx; i++) {
          cur = cur.next;
        }
        return cur.el;
      }
    
      getFirst() {
        return this.get(0);
      }
    
      getLast() {
        return this.get(this.#size - 1);
      }
    
      set(idx, el) {
        if (idx < 0 || idx >= this.#size) {
          throw new Error('Out of bounds!');
        }
        let cur = this.#dummy.next;
        for (let i = 0; i < idx; i++) {
          cur = cur.next;
        }
        cur.el = el;
      }
    
      removeByIndex(idx) {
        if (idx < 0 || idx >= this.#size) {
          throw new Error('Out of bounds!');
        }
        let prev = this.#dummy;
        for (let i = 0; i < idx; i++) {
          prev = prev.next;
        }
        const target = prev.next;
        prev.next = target.next;
        target.next = null;
        this.#size--;
    
        return target;
      }
    
      contains(el) {
        let cur = this.#dummy.next;
        while (cur !== null) {
          if (cur.el === el) {
            return true;
          }
          cur = cur.next;
        }
        return false;
      }
    
      print() {
        let cur = this.#dummy;
        console.info('start: ' );
        while (cur !== null) {
          console.log(cur.el);
          cur = cur.next;
        }
        console.info('end!');
      }
    }
    
    const linkedList = new LinkedList();
    linkedList.addLast(new Node(1))
    linkedList.addLast(new Node(2))
    
    linkedList.print();
  • 相关阅读:
    风讯DotNetCMS sp5安装笔记
    datalist中实现自动编号写法
    windows server 2008 自动登录设置
    C#软件监控外部程序运行状态
    WPF启动屏幕SplashScreen
    Windows Server 2019 在桌面上显示“我的电脑”
    使用jquery的load方法加载html页面,html引入的js无效
    sql查询文章上一篇下一篇
    C#调用user32.dll Win32的API函数
    C#调用dll提示"试图加载格式不正确的程序
  • 原文地址:https://www.cnblogs.com/fanqshun/p/16664771.html
Copyright © 2020-2023  润新知