forked from MohmedIkram/Hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SinglyLinkedList.js
145 lines (128 loc) · 2.81 KB
/
SinglyLinkedList.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
class Node{
constructor(value, next=null){
this.value = value;
this.next = next;
}
}
class SinglyLL{
constructor(){
this.head = null;
this.size = 0;
}
// Insert functionality
insertFirst(value){
let node = new Node(value);
if(this.head === null){
this.head = node;
} else {
node.next = this.head;
this.head = node;
}
this.size +=1;
}
lastInsert(value){
let node = new Node(value);
if(this.head === null){
this.insertFirst(value);
return;
}
let temp = this.head;
while(temp.next !== null){
temp = temp.next;
}
temp.next = node;
this.size +=1;
}
insert(index,value){
if(index === this.size){
this.lastInsert(value);
return;
}
if(index ===0){
this.insertFirst(value);
return;
}
let temp = this.head;
for(let i =1; i<index; i++){
temp = temp.next;
}
let node = new Node(value, temp.next);
temp.next = node;;
this.size +=1;
}
// Delete Functionality;
firstDelete(){
if(this.head === null){
console.log("Empty LL");
return;
}
if(this.head.next === null){
this.head = null;
return;
}
this.head = this.head.next;
this.size -=1;
}
lastDelete(){
if(this.head === null){
console.log('Empty LL');
return;
}
if(this.head.next === null){
this.head = null;
return;
}
let temp = this.head;
while(temp.next.next !== null){
temp = temp.next;
}
temp.next = null;
this.size -=1;
}
delete(index){
if(index === 0){
this.firstDelete();
return;
}
if(index === this.size -1){
this.lastDelete();
return;
}
let temp = this.head;
for(let i=1; i<index; i++){
temp = temp.next;
}
temp.next = temp.next.next;
this.size -=1;
}
//Display
display(){
let temp = this.head;
let answer = "";
while(temp !== null){
answer += `${temp.value} ->`
temp = temp.next;
}
answer += 'END';
console.log(answer);
}
}
let s = new SinglyLL();
s.insertFirst(30);
s.insertFirst(25);
s.insertFirst(22);
s.insertFirst(15);
s.lastInsert(35);
s.lastInsert(40);
s.lastInsert(50);
s.lastInsert(55);
s.insert(2,32);
s.insert(1,27);
s.firstDelete();
s.firstDelete();
s.lastDelete();
s.lastDelete();
s.delete(1);
s.delete(2);
s.display()
console.log(s.size);