-
Notifications
You must be signed in to change notification settings - Fork 0
/
singlylinkedlist.js
43 lines (42 loc) · 950 Bytes
/
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
//With Singly Linked List
//Enqueue --> Add at the end of the list
//Dequeue --> Remove from the beginning ofthe list
class Node{
constructor(value){
this.value = value;
this.next = null;
}
}
class Queue{
constructor(){
this.first = null;
this.last = null;
this.size = 0;
}
enqueue(val){
let newNode = new Node(val);
if (!this.first){
this.first = newNode;
this.last = newNode;
}else{
this.last.next = newNode;
this.last = newNode;
}
this.size++;
return this.size;
}
dequeue(){
if (!this.first){
return null;
}
let prevNode = this.first;
this.first = this.first.next;
prevNode.next = null
this.size--;
if (this.size === 0){
this.last = null;
}
return prevNode;
}
}
let q = new Queue();