Muscardinus

Double Linked List 구현 본문

DataStructure

Double Linked List 구현

Muscardinus 2020. 10. 15. 13:42
728x90
class DoublyLinkedList {
  constructor(value) {
    this.head = {
      value: value,
      next: null,
      prev: null,
    };
    this.tail = this.head;
    this.length = 1;
  }
  append(value) {
    const newNode = {
      value: value,
      next: null,
      prev: null,
    }
    newNode.prev = this.tail;
    this.tail.next = newNode;
    this.tail = newNode;
    this.length++;
    return this;
  }
  prepend(value) {
    const newNode = {
      value: value,
      next: null,
      prev: null,
    }
    newNode.next = this.head;
    this.head.prev = newNode;
    this.head = newNode;
    this.length++;
    return this;
  }
  printList() {
    const array = [];
    let currentNode = this.head;
    while(currentNode !== null){
        array.push(currentNode.value)
        currentNode = currentNode.next
    }
    return array;
  }
  insert(index, value){
    if(index >= this.length) {
      console.log('yes')
      return this.append(value);
    }
    
    const newNode = {
      value: value,
      next: null,
      prev: null,
    }
    const leader = this.traverseToIndex(index-1);
    const follower = leader.next;
    leader.next = newNode;
    newNode.prev = leader;
    newNode.next = follower;
    follower.prev = newNode;
    this.length++;
    return this.printList();
  }
  traverseToIndex(index) {
    let counter = 0;
    let currentNode = this.head;
    while(counter !== index){
      currentNode = currentNode.next;
      counter++;
    }
    return currentNode;
  }
  remove(index) {     
    const leader = this.traverseToIndex(index-1);
    const follower = this.traverseToIndex(index+1);
    const unwantedNode = leader.next;
    leader.next = unwantedNode.next;
    follower.prev = leader;
    this.length--;
    return this.printList();
  }
}
728x90

'DataStructure' 카테고리의 다른 글

Undirected Graph 구현  (0) 2020.12.13
Binary Search Tree 구현  (0) 2020.12.13
Queue 구현  (0) 2020.12.12
Stack 구현  (0) 2020.12.12
Linked List 구현  (0) 2020.10.15
Comments