File tree 1 file changed +84
-0
lines changed
1 file changed +84
-0
lines changed Original file line number Diff line number Diff line change
1
+ class CircularQueue {
2
+ constructor ( capacity ) {
3
+ this . items = new Array ( capacity ) ;
4
+ this . rear = - 1 ;
5
+ this . front = - 1 ;
6
+ this . currentLength = 0 ;
7
+ this . capacity = capacity ;
8
+ }
9
+
10
+ isFull ( ) {
11
+ return this . currentLength === this . capacity ;
12
+ }
13
+
14
+ isEmpty ( ) {
15
+ return this . currentLength === 0 ;
16
+ }
17
+
18
+ size ( ) {
19
+ return this . currentLength ;
20
+ }
21
+
22
+ enqueue ( item ) {
23
+ if ( ! this . isFull ( ) ) {
24
+ this . rear = ( this . rear + 1 ) % this . capacity ;
25
+ this . items [ this . rear ] = item ;
26
+ this . currentLength += 1 ;
27
+ if ( this . front === - 1 ) {
28
+ this . front = this . rear ;
29
+ }
30
+ }
31
+ }
32
+
33
+ dequeue ( ) {
34
+ if ( this . isEmpty ( ) ) {
35
+ return null ;
36
+ }
37
+ const item = this . items [ this . front ] ;
38
+ this . items [ this . front ] = null ;
39
+ this . front = ( this . front + 1 ) % this . capacity ;
40
+ this . currentLength -= 1 ;
41
+ if ( this . isEmpty ( ) ) {
42
+ this . front = - 1 ;
43
+ this . rear = - 1 ;
44
+ }
45
+ return item ;
46
+ }
47
+
48
+ peek ( ) {
49
+ if ( ! this . isEmpty ( ) ) {
50
+ return this . items [ this . front ] ;
51
+ }
52
+ return null ;
53
+ }
54
+
55
+ print ( ) {
56
+ if ( this . isEmpty ( ) ) {
57
+ console . log ( "Queue is empty" ) ;
58
+ } else {
59
+ let i ;
60
+ let str = "" ;
61
+ for ( i = this . front ; i !== this . rear ; i = ( i + 1 ) % this . capacity ) {
62
+ str += this . items [ i ] + " " ;
63
+ }
64
+ str += this . items [ i ] ;
65
+ console . log ( str ) ;
66
+ }
67
+ }
68
+ }
69
+
70
+ const queue = new CircularQueue ( 5 ) ;
71
+ console . log ( queue . isEmpty ( ) ) ;
72
+ queue . enqueue ( 10 ) ;
73
+ queue . enqueue ( 20 ) ;
74
+ queue . enqueue ( 30 ) ;
75
+ queue . enqueue ( 40 ) ;
76
+ queue . enqueue ( 50 ) ;
77
+ console . log ( queue . size ( ) ) ;
78
+ queue . print ( ) ;
79
+ console . log ( queue . isFull ( ) ) ;
80
+ console . log ( queue . dequeue ( ) ) ;
81
+ console . log ( queue . peek ( ) ) ;
82
+ queue . print ( ) ;
83
+ queue . enqueue ( 60 ) ;
84
+ queue . print ( ) ;
You can’t perform that action at this time.
0 commit comments