Ts数据结构(一)单向链表

50 阅读1分钟

e1616baab96d40dcb27cf0e655062c64_tplv-k3u1fbpfcp-zoom-crop-mark_1512_1512_1512_851.webp

单向链表

认识链表

1、链表是一种通过指针的形式把一组存储单元联系在一起的数据结构。 2、链表的主要结构就是如下图

a2f20217b5f34c40bd456a86df9c541b_tplv-k3u1fbpfcp-zoom-in-crop-mark_4536_0_0_0.webp

链表的封装

封装节点类

每一个节点主要是两部分组成,第一个是value用来存储节点的数据,第二个就是next指针来指向下一个节点

//
// 创建node节点类
class myNode<T> {
  value: T;
  next: myNode<T> | null = null;
  constructor(value: T) {
    this.value = value;
  }
}

封装链表类

// 创建链表类
class LinkedList<T> {
  private head: myNode<T> | null = null;
  private size = 0;
  getlength() {
    return this.size;
  }
}

封装通过位置获取节点的方法getNode

// 
// 
private getNode(position: number): myNode<T> | null {
    let index = 0;
    let current = this.head;
    while (index++ < position && current) {
      current = current?.next;
    }
    return current;
  }

封装通过位置获取节点的value的方法getValue

// 
// 
getValue(position: number): T | null {
    let current = this.head;
    let index = 0;
    console.log(this.getNode(position)?.value ?? null);
    return this.getNode(position)?.value ?? null;
  }

封装append 方法

append(value: T) {
    // 创建一个新的节点
    const newNode = new myNode(value);
    // 判断this.head 是否是null
    if (!this.head) {
      this.head = newNode;
    } else {
      let current = this.head;
      while (current.next) {
        current = current.next;
      }
      current.next = newNode;
    }
    this.size++;
  }

封装遍历链表traverse

// 遍历我们的链表
  traverse() {
    const values: T[] = [];
    let current = this.head;
    while (current) {
      values.push(current.value);
      current = current.next;
    }
    console.log(values.join("->"));
  }

封装insert

insert(value: T, position: number): boolean {
    // 临界判断
    if (position > this.size || position < 0) return false;
    // 创建一个新的节点
    const newNode = new myNode(value);
    // 如果position为0
    if (position === 0) {
      newNode.next = this.head;
      this.head = newNode;
    } else {
      let current = this.head;
      current = this.getNode(position);
      let previous = this.getNode(position - 1);
      newNode.next = current;
      previous!.next = newNode;
    }
    this.size++;
    return true;
  }

封装删除remove

removeAt(position: number): T | null {
    // 越界判断
    if (position < 0 || position > this.size) return null;
    // 如果删除的是第一个
    let current = this.head;
    if (position === 0) {
      this.head = current?.next ?? null;
    } else {
      let previous = this.getNode(position -1);
      current = previous?.next ?? null;
      previous!.next = current?.next ?? null;
    }
    return current?.value ?? null;
  }