summaryrefslogtreecommitdiffstats
path: root/linkedlist.js
blob: 8b3f23e82edc0bb63cfc271a461a62a66e724ae8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// linkedlist

// hides scope from global access
(function() {
    function LinkedList() {}

    LinkedList.prototype = {
        length: 0,
        head: null,
        tail: null
    };

    LinkedList.Node = function() {}
    LinkedList.Node.prototype = {
        val: null,
        prev: null,
        next: null
    };

    LinkedList.prototype.add = function(v) {
        var newNode = new LinkedList.Node();
        newNode.val = v;
        newNode.next = this.head;
        if (this.head == null)
            this.tail = newNode;
        else
            this.head.prev = newNode;
        this.head = newNode;
        this.length++;

        // for mutiple call chaining
        return this;
    }

    LinkedList.prototype.remove = function() {
    }

    LinkedList.prototype.size = function() {
        console.log(this.length);
    }

    LinkedList.prototype.print = function() {
        var curr = this.head;
        var res = [];
        while (curr) {
            res.push(curr.val);
            curr = curr.next;
        }
        console.log(res.join(" -> "));
    }

    var ll = new LinkedList();
    var ll2 = new LinkedList();
    ll.add(7).add(12).add(13).add(21);
    ll.print();
    ll.size();

    ll2.add(70).add(120).add(130);
    ll2.print();
    ll2.size();
})();