var head value HEAD next undefined prev undefined function insertAfter

 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
var head = {
value: 'HEAD',
next: undefined,
prev: undefined
};
function insertAfter(where, val) {
var what = {
value: val,
next: undefined,
prev: undefined
}
var nxt = where.next;
where.next = what;
what.next = nxt;
if (nxt !== undefined) {
nxt.prev = what;
}
what.prev = where;
return what;
}
function deleteNode(node) {
if (node.prev !== undefined) {
node.prev.next = node.next;
}
if (node.next !== undefined) {
node.next.prev = node.prev;
}
}
function search(val) {
var current = head;
while (current.next !== undefined) {
if (current.value == val) {
return current;
}
current = current.next;
}
console.log("Not found");
}
function printList() {
var out = '';
var current = head;
while (current !== undefined) {
out += current.value + ' <-> ';
current = current.next;
}
console.log(out);
}
printList();
var helloNode = insertAfter(head, 'hello');
printList();
var worldNode = insertAfter(helloNode, 'world');
printList();
var semicolonNode = insertAfter(helloNode, ',');
printList();
var anotherNode = insertAfter(semicolonNode, 'another');
printList();
deleteNode(anotherNode);
printList();