|
| 1 | +//Implementing Linked List and it's method in Javascript (ES5) |
| 2 | + |
| 3 | +function Node(data){ |
| 4 | + this.data = data; |
| 5 | + this.next = null; |
| 6 | +} |
| 7 | + |
| 8 | +function LinkedList(){ |
| 9 | + this._length = 0; |
| 10 | + this.head = null; |
| 11 | +} |
| 12 | + |
| 13 | +LinkedList.prototype.isEmpty = function(){ |
| 14 | + if(this.head===null){ |
| 15 | + return true; |
| 16 | + }else{ |
| 17 | + return false; |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +LinkedList.prototype.add = function(data){ |
| 22 | + |
| 23 | + if(!data){ |
| 24 | + console.error("No data found"); |
| 25 | + }else{ |
| 26 | + if(this.head === null){ |
| 27 | + this.head = new Node(data); |
| 28 | + }else{ |
| 29 | + var newHead = new Node(data); |
| 30 | + newHead.next = this.head; |
| 31 | + this.head = newHead; |
| 32 | + } |
| 33 | + } |
| 34 | + this._length++; |
| 35 | +} |
| 36 | + |
| 37 | +LinkedList.prototype.contains = function(data){ |
| 38 | + var current = this.head; |
| 39 | + while(current !== null){ |
| 40 | + if(current.data === data){ |
| 41 | + return true; |
| 42 | + } |
| 43 | + current = current.next; |
| 44 | + } |
| 45 | + return false; |
| 46 | +} |
| 47 | + |
| 48 | +LinkedList.prototype.addAt = function(data,where){ |
| 49 | + var current = this.head; |
| 50 | + var prev = null; |
| 51 | + var newNode = new Node(data); |
| 52 | + //debugger |
| 53 | + while(current.data !== where){ |
| 54 | + prev = current; |
| 55 | + current = current.next; |
| 56 | + } |
| 57 | + //prev.next = newNode; |
| 58 | + //newNode.next = current; |
| 59 | + var something = current.next; |
| 60 | + current.next = newNode; |
| 61 | + newNode.next = something; |
| 62 | + |
| 63 | + |
| 64 | +} |
| 65 | + |
| 66 | +LinkedList.prototype.append= function(data){ |
| 67 | + var current = this.head; |
| 68 | + while(current.next !== null){ |
| 69 | + current = current.next; |
| 70 | + } |
| 71 | + current.next = new Node(data); |
| 72 | + this._length++; |
| 73 | +} |
| 74 | + |
| 75 | +LinkedList.prototype.delete = function(data){ |
| 76 | + var current = this.head; |
| 77 | + var prev = null; |
| 78 | + if(this.head.data === data){ |
| 79 | + this.head = this.head.next; |
| 80 | + this._length--; |
| 81 | + return; |
| 82 | + } |
| 83 | + while(current.data !== data){ |
| 84 | + prev = current; |
| 85 | + current = current.next; |
| 86 | + } |
| 87 | + prev.next = current.next; |
| 88 | + this._length--; |
| 89 | +} |
| 90 | +var list = new LinkedList() |
| 91 | +list.add(10); |
| 92 | +list.add(20); |
| 93 | +list.add(30); |
| 94 | +list.add(40); |
| 95 | +list.append(50); |
| 96 | +list.addAt(15,20) |
| 97 | +console.log(list.contains(20)); |
| 98 | +console.log(list) |
0 commit comments