-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinkedList.js
More file actions
123 lines (97 loc) · 2.25 KB
/
linkedList.js
File metadata and controls
123 lines (97 loc) · 2.25 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
var LinkedList = function() {
this.head = null;
};
LinkedList.prototype.push = function( val ) {
var newNode = {
val: val,
next: null
};
if ( this.head ) {
var currentNode = this.head;
while( currentNode.next ) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
} else {
this.head = newNode;
}
return this;
};
LinkedList.prototype.pop = function() {
var removedNode;
if ( !this.head ) {
return null;
} else if( !this.head.next ) {
removedNode = this.head;
this.head = null;
return removedNode;
} else {
// move through the linked list to the last element
var lastElement;
var currentElement = this.head;
while( currentElement.next ) {
lastElement = currentElement;
currentElement = currentElement.next;
}
// remove reference to the element
removedNode = lastElement.next;
lastElement.next = null;
// return the node
return removedNode;
}
};
LinkedList.prototype.remove = function( nodeVal ) {
var currentNode = this.head;
if ( !currentNode ) {
return false;
} else if ( currentNode.val === nodeVal ) {
this.head = this.head.next;
return true;
}
while( currentNode.next ) {
if ( currentNode.next.val === nodeVal ) {
currentNode.next = currentNode.next.next;
return true;
} else {
currentNode = currentNode.next;
}
}
return false;
};
LinkedList.prototype.reverse = function() {
var nodes = [];
if ( !this.head || !this.head.next ) {
return this;
}
// get all nodes
var currentNode = this.head;
while( currentNode.next ) {
nodes.push( currentNode );
currentNode = currentNode.next;
}
nodes.push( currentNode );
var newList = new LinkedList();
while( nodes.length > 0 ) {
var node = nodes.pop();
newList.push( node.val );
}
return newList;
};
LinkedList.prototype.reverseInPlace = function() {
if ( !this.head || !this.head.next ) {
return this;
}
var current = this.head;
var next = this.head.next;
// make current head the tail
current.next= null;
var oldList;
while( next ) {
oldList = next.next;
next.next = current; // reverse
current = next;
next = oldList;
}
this.head = current;
return this;
};