【数据结构】单链表常用方法实现

链表结构

链表配合图才好理解,所以画了以下这些图帮助理解链表工作的流程

插入链表示意图

第一种情况:在链表开头插入元素

第二种情况:在链表除开头的任意位置插入元素

删除链表元素示意图

第一种情况:

第二种情况:

代码实现

class Node {
  constructor(element) {
    this.element = element;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.length = 0;
  }
//在链表尾部插入元素
  append(element) {
    let newNode = new Node(element),
        current;

    if(this.head === null) {
      this.head = newNode;
    } else {
      current = this.head;

      while(current.next) {
        current = current.next;
      }

      current.next = newNode;
    }
    this.length++;
  }
//在链表任意位置插入元素
  insert(element,position) {
    let newNode = new Node(element),
        current = this.head,
        previous,
        index = 0;
    if(position >= 0 && position <= this.length) {
      if(position === 0) {
        this.head = newNode;
        newNode.next = current;
      } else {

        while(index++ < position) {
          previous = current; //记录每一个元素的前一项
          current = current.next; //current指向下一个元素的数据域
        }
        previous.next = newNode; //前一项的指针域指向插入的新元素
        newNode.next = current; //新元素的指针域指向后面的元素
      }
      this.length++;
      return true;
    }else {
      return false;
    }
  }
//获取任意位置元素
  getElem(position) {
    let current = this.head,
        index = 0;
    //判断越界
    if(position < 0 || position > this.length - 1) {
      return null;
    } else {
      // 直到找到index ++到postion,说明已经到了要找的元素位置
      while(index++ < position) {
        current = current.next;
      }
    
      return current.element; //直接返回元素的element
    }
  }
//获取任意位置元素的索引
  indexOf(element) { 
    let current = this.head,
        index = 0;
    
    while(current) {
      if(current.element === element) {
        return index;
      }
        index++;
        current = current.next;
    }

    return -1; //若没找到返回-1
  }
//删除任意位置的元素
  removeAt(position) {
    let current = this.head,
        previous,
        index = 0;
    if(position < 0 || position > this.length - 1) {
      return null;
    } else {
      if(position === 0) {
        this.head = current.next;
      } else {
        // 循环到要删除的位置
        while(index++ < position) {
          previous = current; //记录current前一项
          current = current.next; //current往后移
        }
        current = current.next; //current向后移
        previous.next = current; //previous的指针域直接链接向后移过的current
      }
      this.length--;
      return true;
    }
  }
//更新任意位置的元素
  update(element,position) {
    this.removeAt(position); //先删除这个位置的元素
    return this.insert(element,position); //再插入更新元素
  }
}
posted @ 2021-09-28 17:42  razzh  阅读(103)  评论(0)    收藏  举报