-
Notifications
You must be signed in to change notification settings - Fork 2
/
LinkedList.js
107 lines (84 loc) · 1.57 KB
/
LinkedList.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
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
'use strict'
module.exports = class LinkedList{
constructor(){
this._size = 0;
this.head = null;
}
insertStartNode(node){
node.next = this.head;
this.head = node;
++this._size;
return this;
}
insertEndNode(node){
if(null === this.head){
this.head = node;
++this._size;
return this;
}
let tmp = this.head;
while(tmp.next){
tmp = tmp.next;
}
tmp.next = node;
++this._size;
return this;
}
insertStart(val){
return this.insertStartNode( new Node(val) );
}
insertEnd(val){
return this.insertEndNode( new Node(val) );
}
deleteFirst(){
if(null === this.head){
throw new Error("InvalidOperation, the list is empty.");
}
let n = this.head;
this.head = this.head.next;
n.next = null;
--this._size;
return n;
}
deleteLast(){
if(null === this.head){
throw new Error("InvalidOperation, the list is empty.");
}
let p1 = this.head, p2 = p1.next;
if(null === p2){
this.head = null;
--this._size;
return p1;
}
while(p2.next){
p1= p2;
p2 = p2.next;
}
p1.next = null;
--this._size;
return p2;
}
get length(){
return this._size;
}
traverse(fn){
let tmp = this.head, rstArray = [];
while(tmp){
rstArray.push( fn?fn(tmp.val):tmp.val );
tmp = tmp.next;
}
return rstArray;
}
toString(){
return this.traverse().join(" -> ");
}
clear(){
while(this._size){
this.deleteFirst();
}
}
}
function Node(value){
this.next = null;
this.val = value;
}