-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinked_List.js
94 lines (83 loc) · 2.07 KB
/
Linked_List.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
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class List {
constructor() {
this.head = null;
this.size = 0;
}
add(element) {
let node = new Node(element);
let actual = null;
if (this.head == null) {
this.head = node;
} else {
actual = this.head;
while (actual.next) {
actual = actual.next;
}
actual.next = node;
}
this.size++;
}
delete(element) {
let actual = this.head;
let past = null;
while (actual != null) {
if (actual.element === element) {
if (past === null) {
this.head = actual.next;
} else {
past.next = actual.next;
}
this.size--;
return actual.element;
}
past = actual;
actual = actual.next;
}
return -1;
}
deleteFirst() {
let actual = this.head;
if (this.size >0 ) {
// console.log(this.size);
// console.log(actual.next);
this.head = actual.next;
// console.log(this.size);
this.size--;
} else {
this.head=null;
console.log(`Nothing to delete`);
}
}
deleteLast() {
let actual = this.head;
let past = null;
if(this.size>0){
while (actual.next) {
past = actual;
actual = actual.next;
past.next = actual.next;
this.size--;
}
}else {
this.head=null;
console.log(`Nothing to delete in deleteLast`);
}
}
printList() {
let actual = this.head;
let data = "";
while (actual) {
data += actual.element + " ";
actual = actual.next;
}
console.log(data);
}
}
/************************ */
const list = new List();