-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_as_doubly_linked_list.js
109 lines (107 loc) · 1.94 KB
/
queue_as_doubly_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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
class Node
{
constructor(data)
{
this.nextNode = null;
this.previousNode = null;
this.data = data;
}
}
class DoublyLinkedList
{
constructor(firstNode = null, lastNode = null)
{
this.firstNode = firstNode;
this.lastNode = lastNode;
}
InsertAtEnd(data)
{
let newNode = new Node(data);
if(this.lastNode)
{
this.lastNode.nextNode = newNode;
this.lastNode = this.lastNode.nextNode;
return
}
this.firstNode = newNode;
this.lastNode = newNode;
}
RemoveFromStart()
{
if(this.firstNode && this.lastNode && (this.firstNode !== this.lastNode))
{
let nextToFirst = this.firstNode.nextNode;
this.firstNode = nextToFirst;
}
else
this.firstNode = null;
}
Print()
{
console.log('--------printing--------');
if(!this.firstNode)
{
console.log('Empty Doubly Linked List');
return;
}
let currentNode = this.firstNode;
while(true)
{
console.log(currentNode.data);
if(!currentNode.nextNode)
{
break;
}
currentNode = currentNode.nextNode;
}
//console.log('--------printing--------');
}
}
class Queue
{
constructor()
{
this.queue = new DoublyLinkedList();
}
Enqueue(data)
{
this.queue.InsertAtEnd(data);
}
Dequeue()
{
this.queue.RemoveFromStart();
}
Print()
{
this.queue.Print();
}
}
let a = new Node('Hola');
let b = new Node('Como');
let c = new Node('Estas');
a.nextNode = b;
b.nextNode = c;
let dll = new DoublyLinkedList(a, b);
dll.InsertAtEnd("?");
dll.Print();
let dll1 = new DoublyLinkedList();
dll1.Print();
dll1.InsertAtEnd('hola');
dll1.Print();
dll1.InsertAtEnd('cómo');
dll1.Print();
dll1.InsertAtEnd('estás?');
dll1.Print();
dll1.RemoveFromStart();
dll1.Print();
dll1.RemoveFromStart();
dll1.Print();
dll1.RemoveFromStart();
dll1.Print();
let q = new Queue();
q.Enqueue('hola');
q.Enqueue('Cómo');
q.Enqueue('Me');
q.Print();
q.Dequeue();
q.Print();