数据结构-链表

// 节点
class Node {
  constructor(element) {
    this.element = element
    this.next = null
  }
}

// 链表
class LinkList {
  constructor() {
    this.size = 0
    this.head = null
  }

  // 根据index获取节点
  getNode(index) {
    if (index < 0 || index > this.size) {
      throw new Error('out range')
    }

    let current = this.head
    for (let i = 0; i < index; i++) {
      current = current.next
    }
    return current
  }
  // 反转链表
  reverse(p = this.head) {
    // p.next 递归中指条件 p指向最后面
    if (p.next) {
      // 如果有下个指针则递归
      this.reverse(p.next)
      p.next.next = p
      p.next = null
    } else {
      this.head = p
    }
  }

  // 追加元素
  append(element) {
    let node = new Node(element)
    if (this.head === null) {
      // 第一次初始化
      this.head = node
    } else {
      // 链表中有内容
      // 获取当前的最后一个节点
      let current = this.getNode(this.size - 1)
      current.next = node
    }

    this.size++
  }
  // 特定位置添加
  appendAt(position, element) {
    if (position < 0 || position > this.size) {
      throw new Error('position out range')
    }
    let node = new Node(element)

    if (position === 0) {
      // 如果在最前添加
      node.next = this.head
      this.head = node
    } else {
      // 如果在中间添加
      let pre = this.getNode(position - 1)
      node.next = pre.next
      pre.next = node
    }
    this.size++
  }
  // 删除特定链表
  removeAt(position) {
    if (position < 0 || position >= this.size) {
      throw new Error('position out range')
    }
    let current = this.head
    if (position === 0) {
      // 删除头
      this.head = current.next
    } else {
      let pre = this.getNode(position - 1)
      current = pre.next
      pre.next = current.next
    }
    this.size--
  }
  // 查找指定元素索引
  indexOf(element) {
    let current = this.head
    for (let i = 0; i < this.size; i++) {
      if (current.element === element) {
        return i
      }
      current = current.next
    }
    return -1
  }
}

let ll = new LinkList()
ll.append(1)
ll.append(2)
// ll.append(3)
// ll.append(4)
ll.appendAt(2, 3)
ll.appendAt(3, 4)
// ll.appendAt(3, 2)
// ll.removeAt(1)
// console.log(ll.indexOf(1))
console.log(ll.reverse())
console.dir(ll, {
  depth: 100,
})

 

posted @ 2023-10-20 12:10  佳佳460  阅读(6)  评论(0)    收藏  举报