如何在ReactJS组件中呈现LinkedList

icomxhvb  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(98)
class Node {
    constructor(value) {
      this.value = value;
      this.next = null;
    }
  }
  
  class LinkedList {
    constructor() {
      this.head = null;
      this.tail = null;
      this.length = 0;
    }
  
    addToTail(value) {
      let newNode = new Node(value);
  
      if (!this.head) {
        this.head = newNode;
        this.tail = newNode;
      } else {
        this.tail.next = newNode;
        this.tail = newNode;
      }
  
      this.length++;
      return this;
    }
  
    removeFromTail() {
      if (!this.head) return null;
  
      let current = this.head;
      let newTail = current;
  
      while (current.next) {
        newTail = current;
        current = current.next;
      }
  
      this.tail = newTail;
      this.tail.next = null;
      this.length--;
  
      if (this.length === 0) {
        this.head = null;
        this.tail = null;
      }
  
      return current;
    }
  
    addToHead(value) {
      let newNode = new Node(value);
      if (!this.head) {
        this.head = newNode;
        this.tail = newNode;
      } else {
        newNode.next = this.head;
        this.head = newNode;
      }
      this.length++;
      return this;
    }
  
    removeFromHead() {
      if (!this.head) return null;
      let currentHead = this.head;
      this.head = currentHead.next;
      this.length--;
      return currentHead;
    }
  }

如何在reactjs组件中呈现linkedlist中的项,就好像从数组中Map出元素一样,而不是在这个linkedlist类中。
我在实现不同的类时遇到了困难,比如在Java中,你必须从不同的文件中扩展类,除了在ReactJS中和使用javascript之外,还有什么是等效的呢?

p5fdfcr1

p5fdfcr11#

将列表转换为数组

function getItems() {
  let current = list.head
  const array = []
  while (current) {
    array.push(current)
    current = current.next
  }
}

然后照常渲染

<>{ getItems().map(item => <div>{item}</div>) }</>

相关问题