JSFiddle - React, Tailwind, and code Playground

by Erik East

HTML

<h2>Module 03</h2>
<h3>Assignment 1</h3>
<p id="output"></p>

JavaScript

var LinkedList = function () {

    this.head = null;
    this.tail = null;
    
    var LinkedListNode = function (content) {
        this.next = null;
        this.content = content;
    };

    this.add = function (content) {
        // No head - create one
        if (this.head == null) {
            this.head = new LinkedListNode(content);
            return this.head;
        }

        // No  tail - create one
        if (this.tail == null) {
            this.tail = new LinkedListNode(content);
            this.head.next = this.tail;
            return this.tail;
        };

        this.tail.next = new LinkedListNode(content);
        this.tail = this.tail.next;
        this.tail.next = null;
        return this.tail;
    };    
}

LinkedList.prototype.length  = function () {
        var i = 0;
        var node = this.head;

        while (node != null) {
            i++;
            node = node.next;
        }
        return i;
    };

LinkedList.prototype.toString = function () {
    var i = 1;
    var str = 'Linked List with ' + this.length() + ' nodes <br/>';
    var node = this.head;


    while (node != null) {
        str += i + ':  Node Value: ' + node.content + "<br>";
        str += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Next Node Value: ';

        if (node.next == null) str += ' null';

        if (node.next != null) str += node.next.content;

        i++;
        str += '<br/>';
        node = node.next;
    }
    return str;
};

// Create a Linked List and Add Nodes

var ll = new LinkedList();

ll.add('Node1');
ll.add('Node2');
ll.add('Node3');
ll.add('Node4');
ll.add('Node5');

document.getElementById('output').innerHTML = ll.toString();