Skip to content

Commit 31e97c6

Browse files
add queue
1 parent c5dc414 commit 31e97c6

File tree

4 files changed

+57
-2
lines changed

4 files changed

+57
-2
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@
88
3. [Сортировка подсчётом](https://github.com/dmitrymorozoff/algorithms-in-javascript/blob/master/source/sorts/counting-sort.js)
99

1010
## Структуры данных
11-
1. [Стек](https://github.com/dmitrymorozoff/algorithms-in-javascript/blob/master/source/structures/stack.js)
11+
1. [Стек](https://github.com/dmitrymorozoff/algorithms-in-javascript/blob/master/source/structures/stack.js)
12+
2. [Очередь](https://github.com/dmitrymorozoff/algorithms-in-javascript/blob/master/source/structures/queue.js)

index.html

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
<script src="./source/sorts/counting-sort.js" type="modul≠e"></script>
1414
<script src="./source/sorts/selection-sort.js" type="module"></script>
1515
<script src="./source/structures/stack.js" type="module"></script>
16+
<script src="./source/structures/queue.js" type="module"></script>
1617
<script src="./source/main.js" type="module"></script>
1718
</body>
1819

source/structures/queue.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
class Node {
2+
constructor(data) {
3+
this.data = data;
4+
this.next = null;
5+
}
6+
}
7+
8+
export default class Queue {
9+
constructor(data) {
10+
this.head = null;
11+
this.size = 0;
12+
}
13+
enqueue(data) {
14+
const newNode = new Node(data);
15+
if (this.head === null && this.size < 1) {
16+
this.head = newNode;
17+
} else {
18+
newNode.next = this.head;
19+
this.head = newNode;
20+
}
21+
this.size++;
22+
}
23+
dequeue() {
24+
if (this.size === 0) {
25+
return;
26+
}
27+
if (this.size === 1) {
28+
return this.head;
29+
}
30+
let current = this.head;
31+
while (current.next.next !== null) {
32+
current = current.next;
33+
}
34+
this.last = current;
35+
let popElement = current.next;
36+
current.next = null;
37+
this.size--;
38+
return popElement;
39+
}
40+
peek() {
41+
let current = this.head;
42+
while (current.next !== null) {
43+
current = current.next;
44+
}
45+
return current;
46+
}
47+
print() {
48+
let iterator = this.head;
49+
while (iterator !== null) {
50+
console.log(iterator.data);
51+
iterator = iterator.next;
52+
}
53+
}
54+
}

source/structures/stack.js

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,6 @@ export default class Stack {
3333
if (this.size === 1) {
3434
return this.head;
3535
}
36-
3736
let current = this.head;
3837
while (current.next.next !== null) {
3938
current = current.next;

0 commit comments

Comments
 (0)