-
Notifications
You must be signed in to change notification settings - Fork 60
/
single-linked-node.js
42 lines (37 loc) · 1.08 KB
/
single-linked-node.js
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
var SinglyLinkedList = function(){}
SinglyLinkedList.prototype = {
addBottom: function(node) {
if (this.head == undefined) return this.head = node;
var currentNode = this.head;
while(currentNode.next !== undefined) {
currentNode = currentNode.next;
}
currentNode.next = node;
},
find: function(data) {
var currentNode = this.head;
while(currentNode !== undefined) {
if(currentNode.data == data) return currentNode;
currentNode = currentNode.next;
}
},
addTop: function(node) {
if (this.head == undefined) return this.head = node;
node.next = this.head;
this.head = node;
},
remove: function(data) {
if (this.head.data == data) return this.head = this.head.next;
var prevNode = this.head;
var currentNode = this.head.next;
while(currentNode !== undefined) {
if(currentNode.data == data) {
prevNode.next = currentNode.next;
return currentNode.next = undefined;
}
prevNode = currentNode;
currentNode = currentNode.next;
}
}
}
module.exports = SinglyLinkedList;