设计链表 leetcode

707. 设计链表

设计链表 leetcode

 

 单链表

class MyLinkedList {
  constructor () {
    this.data = null
  }
  // 获取链表中第 index 个节点的值。如果索引无效,则返回-1
  get (index) {
    let curr = this.data
    for (let i = 0; i < index; i++) {
      if (!curr) break
      curr = curr.next
    }
    return curr ? curr.val : -1
  }
  // 在链表的第一个元素之前添加一个值为 val 的节点。插入后,新节点将成为链表的第一个节点
  addAtHead (val) {
    this.data = { val, next: this.data }
  }
  // 将值为 val 的节点追加到链表的最后一个元素
  addAtTail (val) {
    let curr = this.data
    if (!curr) return this.data = { val, next: null }
    while (curr.next) {
      curr = curr.next
    }
    curr.next = { val, next: null }
  }
  // 在链表中的第 index 个节点之前添加值为 val  的节点。如果 index 等于链表的长度,则该节点将附加到链表的末尾。如果 index 大于链表长度,则不会插入节点。如果index小于0,则在头部插入节点
  addAtIndex (index, val) {
    if (index <= 0) return this.addAtHead(val)
    let curr = this.data
    index--
    while (index && curr.next) {
      index--
      curr = curr.next
    }
    if (index > 0) return
    let tmp = curr.next
    curr.next = { val, next: tmp }
  }
  // 如果索引 index 有效,则删除链表中的第 index 个节点
  deleteAtIndex (index) {
    let curr = this.data, prev = null
    if (!curr) return
    if (index === 0) return this.data = curr.next
    while (index && curr.next) {
      index--
      prev = curr
      curr = curr.next
    }
    if (index > 0) return
    prev.next = curr.next
  }
}

 

双链表

class MyLinkedList {
  constructor () {
    this.data = null
  }
  get(index) {
    if (index < 0) return -1
    let curr = this.data
    while (index > 0 && curr) {
      curr = curr.next
      index--
    }
    return curr ? curr.val : -1
  }
  addAtHead(val) {
    this.data = {
      val, next: this.data, prev: null
    }
    if (this.data.next) this.data.next.prev = this.data
  }
  addAtTail(val) {
    if (this.data) {
      let curr = this.data
      while (curr.next) {
        curr = curr.next
      }
      curr.next = { val, next: null, prev: curr}
    } else {
      this.data = { val, next: null, prev: null }
    }
  }
  addAtIndex(index, val) {
    if (index <= 0) return this.addAtHead(val)
    let curr = this.data
    for (let i = 0; i < index - 1; i++) {
      if (!curr || !curr.next) return null
      curr = curr.next
    }
    if (!curr) return null
    let temp = curr.next
    curr.next = {
      val, prev: curr, next: curr.next
    }
    if (temp) temp.prev = curr.next
  }
  deleteAtIndex(index) {
    if (index < 0) return null
    let curr = this.data
    while (index > 0) {
      if (!curr) return null
      curr = curr.next
      index--
    }
    if (!curr) return null
    if (!curr.prev && !curr.next) {
      this.data = null
    } else if (!curr.prev) {
      curr.next.prev = curr.prev
      this.data = curr.next
    } else if (!curr.next) {
      curr.prev.next = null
    } else {
      curr.prev.next = curr.next
      curr.next.prev = curr.prev
    }
  }
}

 

上一篇:定义一个字符链表并反转


下一篇:python json_tools对比两个json是否相等