Singly Linked List

by willystyle

JavaScript

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

class SinglyLinkedList {
    constructor() {
        this.head = null;        
        this.length = 0;
    }
    push(val) {
        let newNode = new Node(val);
        let current;
        if (this.head == null) {
        	  this.head = newNode; 
        } else { 
        	  current = this.head;   
            while (current.next) { 
                current = current.next; 
            }
            current.next = newNode; 
        }        
        this.length++;
        return this;
    }
}

var list = new SinglyLinkedList;

list.push(1);
list.push(2);
console.log(list.length);