JS实现数据结构-单链表

355 阅读1分钟

1.单链表

  • 链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
  • 特点:插入的时间复杂度O(1),比线性表快得多,但是查找需要O(n),而线性表和顺序表相应的时间而线性表和顺序表相应的时间复杂度分别是O(logn)和O(1)。
// 单链表的优点,插入O(1) 查找O(n)

// 创建一个节点 element存储信息,next指向下一个节点
class Node {
  constructor(element) {
    this.element = element;
    this.next = null
  }
}
class LinkList {
  constructor() {
    this.head = null;
    this.length = 0;
  }
  // append 追加元素
  append(element) {
    // 创建一个节点
    const node = new Node(element)
    // 记录当前位置 current
    let current = null;
    if(this.head === null) {
      // 将node节点直接赋值给head
      this.head = node
    }else {
      // 从head开始循环找出最后一个next为null,再将current.next赋值上
      current = this.head;
      while(current.next) {
        current = current.next
      }
      current.next = node;
    }
    this.length++
  }

  // 找出链表某个元素所在的位置 index = -1
  indexOf(elemet) {
    let index = -1;
    let current = this.head;
    while(current.next) {
      if(elemet === current.element) {
        return index + 1
      }
      index++;
      current = current.next
    }
    return -1
  }

  // 找出postion所在的元素
  getElementAt(position) {
    if(position < 0 || position >= this.length) {
      return null
    }
    let current = this.head
    for(let i = 0; i < position; i++) {
      current = current.next
    }
    return current;
  }

  // 插入具体位置
  insert(position, element) {
    // 创建node节点
    const node = new Node(element);
    // 防止越界
    if(position < 0 || position > this.length) {
      return null;
    }
    // 如果position为0,则直接插入到this.head
    if (position === 0) {
      node.next = this.head;
      this.head = node
    } else {
      let previous = this.getElementAt(position - 1);
      node.next = previous.next;
      previous.next = node;
    }
    this.length++
  }

  // 删除指定的position
  removeAt(position) {
    if(position < 0 || position > this.length) {
      return null
    }
    // 获取到
    let current = this.head
    if(position === 0) {
      this.head = current.next;
    }else {
      let previous = this.getElementAt(position - 1)
      current = previous.next;
      previous.next = current.next;
    }
    this.length--
  }

  // 删除指定的element
  remove(element) {
    const position = this.indexOf(element)
    this.removeAt(position);
  }
}

let list = new LinkList()
list.append('name')
list.append('age')
list.append('leng')
list.append('last')
console.log(list);

// const index = list.indexOf('leng');
// console.log(index); // 2

// console.log(list.indexOf('where'))

// console.log(list.getElementAt(2))

list.insert(2, 'man')

console.log(list)

list.removeAt(2)

list.remove('age')
console.log(list)