JSFiddle - React, Tailwind, and code Playground

by HSilvaDaytona

HTML

Linked Lists<br/>
    <br/><br />
    <input type="button" value="Create List" id="linked" />
    <br /><br /> Name of Node being added:
    <input id="LinkName" Value="A B C D E" />
    <input type="button" value="Add Node to List" id="addNode" />
    <p id="demo"></p>
    <br />

JavaScript

var list = null;
	  
	  document.getElementById("linked").onclick =function(){
		createList();
	}
	
	 document.getElementById("addNode").onclick =function(){
		addNode();
	}

        function createList() {
            var value = document.getElementById("LinkName").value;
            list = new List(value);
            document.getElementById("demo").innerHTML = list.print();
        }


        function addNode() {
            var value = document.getElementById("LinkName").value;
            list.addNode(value,list.last);
            document.getElementById("demo").innerHTML = list.print();
        }


        // Define the link object
        function Node(_value, _last) {
            // This is a possible implementation of a Doubly Linked List
            this.value = _value; // The value stored
            this.last = _last; // A pointer to the previous link
            this.next = null; // a pointer to the next link
            return this; // returns the created node
        }

        Node.prototype.asString = function () {
            return this.value + " ";
        }


        // Define the List object
        function List(_value) {
            this.length = 1;
            this.head = new Node(_value, null);
            this.last = this.head; 
        }

        //Function to add node to list 
        List.prototype.addNode = function (_value,_last) {
            var node = new Node(_value, _last);

            if (this.length) {
                this.last.next = node; 
                node.last = this.last;
                this.last = node;
            } else {
                this.head = node;
                this.last = node;
            }

            this.length++;
        }

        List.prototype.print = function () {
            var s = "";
            var n = this.head;

            while (n != null) {
                s += n.asString();
                n = n.next;
            }

            return s;
        }