JSFiddle - React, Tailwind, and code Playground

by mschock

JavaScript

function LinkedList() {
  this.head = null;
}

function Node(val) {
  this.val = val;
  this.next = null;
}

LinkedList.prototype.add = function(val) {
  var node = new Node(val);
  if (!this.head) {
    this.head = node;
  } else {
    node.next = this.head;
    this.head = node;
  }
  return this;
}

LinkedList.prototype.toString = function() {
  var current = this.head,
    st = '';
  while (current) {
    st += current.val + ' -> ';
    current = current.next;
  }
  return st + 'null';
}

var list = new LinkedList();
list.add(28).add(21).add(17).add(7);
console.log(list.toString());

LinkedList.prototype.reverse = function() {
  var next,
    current = this.head,
    prev = null;

  while (current.next) {
    next = current.next;
    current.next = prev;
    prev = current;
    current = next;
  }

  current.next = prev;
  this.head = current;
  return this;
}

console.log(list.reverse().toString());