Reversing a Linked List

// --------------------------
// reversing a linked list
// --------------------------
//
// iterative solution only.
// recursive solution is in ref below
// https://wsvincent.com/javascript-reverse-linked-list/

// this is what a linked list object is
// super simple version
class LinkedListNode {
  constructor(value) {
    this.value = value;
    this.next = null;
    // singly linked list (no previous)
  }

  printAll() {
    let node = this;
    while (node) {
      console.log("current node.value is: ", node.value);

      if (node.next === null) return;
      node = node.next;
    }
  }
}

const chk = new LinkedListNode(10);
chk.next = new LinkedListNode(2);
chk.next.next = new LinkedListNode(5);
chk.next.next.next = new LinkedListNode(99);

console.log("chk", chk); // this is very explanatory of what a linked list is
chk.printAll();

// to reverse a linked list iteratively

// O(n) time and O(1) space
const reverse = (head) => {
  let node = head;
  let previous;
  let temp;

  while (node) {
    // save next
    temp = node.next;

    // reverse pointer
    node.next = previous;

    // step forward
    previous = node;
    node = temp; // .next
  }

  return previous;
};

// linked list of [1,2,3]
const head = new LinkedListNode(1);
head.next = new LinkedListNode(2);
head.next.next = new LinkedListNode(3);

const reversedHead = reverse(head);

console.log("reversed", reversedHead);
reversedHead.printAll();

// TODO: reverse a double linked list
class DoublyLinkedListNode {
  constructor(value = null, prev = null) {
    this.value = value;
    this.next = null;
    this.prev = prev;
  }

  printAll() {
    let node = this;
    while (node) {
      console.log("current node.value is: ", node.value);

      if (node.next === null) return;
      node = node.next;
    }
  }
}

const head2 = new DoublyLinkedListNode(5);
head2.next = new DoublyLinkedListNode(10, head2);
head2.next.next = new DoublyLinkedListNode(15, head2.next);

console.log("double linked list", head2);
head2.printAll();