-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.js
More file actions
67 lines (59 loc) · 1.12 KB
/
queue.js
File metadata and controls
67 lines (59 loc) · 1.12 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
// Implementing Queues using Singly Linked List
class Queue{
constructor(){
this.head = null;
this.tail = null;
}
enqueue(val){
if(!this.head){
this.head = new QueueNode(val);
this.tail = this.head;
return this;
}
this.tail.next = new QueueNode(val);
this.tail = this.tail.next;
return this;
}
dequeue(){
if(!this.head){
return this;
}
var temp = this.head;
this.head = this.head.next;
return temp;
}
display(){
var str = ''
var curr = this.head
while(curr){
str += curr.val + "-->"
curr = curr.next;
}
return str;
}
contains(val){
if(!this.head){
return "Queue is empty";
}
var curr = this.head;
while(curr){
if(curr.val == val){
return curr;
}
curr = curr.next;
}
return null;
}
}
class QueueNode{
constructor(val){
this.val = val;
this.next = null;
}
}
var q = new Queue();
q.enqueue(5).enqueue(4).enqueue(3);
console.log(q.display());
console.log("Dequeued",q.dequeue().val);
console.log(q.display());
console.log("Contains 3?", q.contains(3));