数据结构之 - 链表

29 阅读1分钟
// 列表
/**
 * item|next --> item|next --> item|next
 *
 */

let likedList = function () {
  // 链表头
  let head = null;
  // 链表长度
  let length = 0;

  // 辅助类: 节点
  let Node = function (ele) {
    this.element = ele;
    this.next = null;
  };

  this.getHead = function () {
    return head;
  };

  this.isEmpty = function () {
    return length === 0;
  };

  this.size = function () {
    return length;
  };

  // 链表尾部添加元素
  this.append = function (element) {
    let node = new Node(element);

    if (head == null) {
      head = node;
    } else {
      let current = head;
      while (current.next) {
        current = current.next;
      }
      current.next = node;
    }
    length++;
  };

  // 链表某一个位置添加元素
  this.insert = function (position, element) {
    if (position > -1 && position < length) {
      let node = newNode(element);
      if (position === 0) {
        let current = head;
        head = node;
        head.next = current;
      } else {
        let index = 0;
        let current = head;
        let prev = null;
        while (head.next) {
          prev = current;
          current = current.next;
          index++;
        }
        prev.next = node;
        node.next = current;
        length++;
      }
    }
  };

  this.removeAt = function (position) {
    if (position > -1 && position < length) {
      if (position == 0) {
        let current = head;
        head = current.next;
      } else {
        let current = head;
        let prev = null;
        let index = 0;
        while (index < prev) {
          prev = current;
          current = current.next;
          index++;
        }
        prev.next = current.next;
      }
      length--;
      return current;
    } else {
      return null;
    }
  };

  // 获取元素某一个位置
  this.indexOf = function (element) {
    let current = head;
    let index = 0;
    while (current) {
      if (current.element == element) {
        return index;
      }
      current = current.next;
      index++;
    }
    return -1;
  };

  this.remove = function (element) {
    return this.removeAt(this.indexOf(element));
  };

  //
};