-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathsingly-list.js
More file actions
102 lines (101 loc) · 2.62 KB
/
singly-list.js
File metadata and controls
102 lines (101 loc) · 2.62 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
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
export default class SinglyList {
constructor(data) {
this.head = null;
this.size = 0;
}
addFirst(data) {
const newNode = new Node(data);
if (this.head === null && this.size < 1) {
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.size++;
}
addLast(data) {
const newNode = new Node(data);
if (this.head === null && this.size < 1) {
this.head = newNode;
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = newNode;
}
this.size++;
}
insert(data, index) {
const newNode = new Node(data);
if (index < 0) {
return;
} else if (index === 0) {
this.addFirst(newNode.data);
} else if (index >= this.size) {
this.addLast(newNode.data);
} else {
let iterator = 0;
let current = this.head;
while (iterator !== index - 1) {
current = current.next;
iterator++;
}
newNode.next = current.next;
current.next = newNode;
}
this.size++;
}
searchNodeAt(index) {
if (index < 0 || index > this.size) {
return;
} else if (index === 0) {
return this.head;
} else {
let current = this.head;
let iterator = 0;
while (current.next !== null) {
if (iterator === index) {
return current;
}
current = current.next;
iterator++;
}
}
}
remove(index) {
if (index < 0 || index >= this.size) {
return;
} else if (index === 0) {
const temp = this.head.next;
this.head = temp;
this.size--;
return;
} else {
let current = this.head;
let iterator = 0;
while (iterator !== index - 1) {
current = current.next;
iterator++;
}
current.next = current.next.next;
}
this.size--;
}
length() {
return this.size;
}
print() {
let iterator = this.head;
while (iterator !== null) {
console.log(iterator.data);
iterator = iterator.next;
}
}
}