JSFiddle - React, Tailwind, and code Playground

by DigitalBiscuits

HTML

<pre class="initial">initial</pre>
<pre class="final"></pre>

JavaScript

/*---Simple reversal---*/
/*
var list1 = [
{id: 8, p: 4},
{id: 4, p: 6},
{id: 6, p: 9},
{id: 9, p: null}
];
function reverseList(list) {
	list.forEach(function(val, idx) {
  	list[idx].p = list[idx-1] ? list[idx-1].id : null;
  });
};

document.querySelector('.initial').innerText = JSON.stringify(list1);
reverseList(list1);
document.querySelector('.final').innerText = JSON.stringify(list1);
*/




/*---------------Linked list with recursive reversal------------------*/

// ListItem class
var ListItem = function(id, pointer, value) {
	this._id = id;
  this._p = pointer;
  this.value = value;
};
ListItem.prototype.next = function() {
  return this._p;
};
ListItem.prototype.toString = function() {
  return JSON.stringify({
  	id: this._id,
 		p: this._p ? this._p._id : null,
  	val: this.val
  });
};
ListItem.prototype.toJSON = function() {
  return {
  	id: this._id,
 		p: this._p ? this._p._id : null,
  	val: this.val
  };
};


// SimpleList class
var SimpleList = function() {
	this.items = [];	//array of type ListItem
};

SimpleList.prototype.addItem = function(id, value) {
 	// add new list item
  this.items.push(new ListItem(id, null, value));
  
  // update last item pointer
  if (this.items.length > 1) {
  	this.items[this.items.length-2]._p = this.items[this.items.length-1];
  }
  
};

SimpleList.prototype.toString = function() {
	return JSON.stringify(this.items);
};

SimpleList.prototype._reverse = function(current, newPointer) {
	//console.log(current, newPointer);
	if (current) {
    var nextPtr = current.next();
    current._p = newPointer;

		return this._reverse(nextPtr, current);
  } else {
  	return null;
  }
};

SimpleList.prototype.reverse = function() {
	if (this.items.length) {
		this._reverse(this.items[0], null);
  }
};

// -------------------------------------------------------


// create our linked list and add new items
var myList = new...