Javascript 中的双向链表,带上下文的导航

当需要上一个和下一个元素的上下文时,双向链表非常有用 - 想象一下浏览照片库,其中每个图像都显示其相邻图 像以供参考。我们不使用索引,而是将当前节点直接存储在组件状态中。

示例

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

class DoublyLinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
  }

  add(value) {
    const newNode = new Node(value);
    if (!this.head) {
      this.head = newNode;
      this.tail = newNode;
    } else {
      this.tail.next = newNode;
      newNode.prev = this.tail;
      this.tail = newNode;
    }
  }
}

const imageList = new DoublyLinkedList();
imageList.add({ id: 1, src: 'image1.jpg', alt: 'First Image' });
imageList.add({ id: 2, src: 'image2.jpg', alt: 'Second Image' });
imageList.add({ id: 3, src: 'image3.jpg', alt: 'Third Image' });

function Gallery() {
  const [currentNode, setCurrentNode] = useState(imageList.head);

  return (
    <div>
      {currentNode.prev && (
        <img src={currentNode.prev.value.src} alt={currentNode.prev.value.alt} className="prev-image" />
      )}
      <img src={currentNode.value.src} alt={currentNode.value.alt} className="main-image" />
      {currentNode.next && (
        <img src={currentNode.next.value.src} alt={currentNode.next.value.alt} className="next-image" />
      )}
      <div>
        <button onClick={() => setCurrentNode(currentNode.prev)} disabled={!currentNode.prev}>
          Previous
        </button>
        <button onClick={() => setCurrentNode(currentNode.next)} disabled={!currentNode.next}>
          Next
        </button>
      </div>
    </div>
  );
}

在这个 React 组件中:

  • 当前节点存储在状态中,UI 根据是否存在上一个或下一个节点进行更新。

  • 这些按钮使用户能够向前和向后导航列表,如果没有更多节点可移动到,则禁用。

  • 这种结构利用周围元素的上下文来模拟实时导航,通常用于轮播、媒体库或播放列表等 UI 组件中。