接続リスト


1.磁気参照構造体

  • は、同じ種類の異なる構造体を指すポインタを含む構造体
  • を含む.
  • の複数のノードから構成される.
  • 各ノードには、データと次のノードが何であるかを示すアドレスがあります.
  • は、新しいデータを追加および削除する機能を有する、
  • .
  • は、jsにおいて配列として実装されている.
  • const LinkedList = () => {
      function LinkedList() {
        this.length = 0;
        this.head = null;
      }
      function Node(data) {
        this.data = data;
        this.next = null
      }
      return LinkedList;
    }
  • LinkListには長さとhead変数があり、それぞれノードの数と最初のノードのアドレスを指す.
  • 2.接続リストの追加、検索、削除

    const LinkedList = () => {
      function LinkedList() {
        this.length = 0;
        this.head = null;
      }
      function Node(data) {
        this.data = data;
        this.next = null
      }
    
    // add
    LinkedList.prototype.add = value => {
      let node = new Node(value);
      let current = this.head;
      //현재 연결리스트에 아무 노드도 없다면,
      if(!current) {
        // head에 새 노드 추가해주고, 길이를 1증가
        this.head = node;
        this.length++;
        return node;
      } else { //노드가 있다면,
        while(current.next) { // 마지막 노드를 찾는다
          current = current.next;
        }
        current.next = node; // 마지막 노드위치에 노드를 추가
        this.length++;
        return node;
    };
      
    LinkedList.prototype.search = position => {
      let current = this.head;
      let count = 0;
      while(count < position) {
        current = current.next;
        count++;
      }
      return current.data
    };
      
    LinkedList.prototype.remove = position => {
      let current = this.head;
      let before, remove;
      let count = 0;
      
      if(position === 0) { // 맨 처음 노드 삭제시
        remove = this.head;
        this.length--;
        return remove;
      } else { // 그 외의 노드를 삭제하면
        while(count < position) {
          before = current;
          count++;
          current = current.nextl
        }
        remove = current;
        before.next = current.next;
        // remove 메모리정리
        this.length--;
        return remove;
      }
    };
      return LinkedList;
    }();