File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ // implementation of Queue using 2 stacks
2+ // contribution made by hamza chabchoub for a university project
3+
4+ class Queue {
5+ constructor ( ) {
6+ this . inputStack = [ ]
7+ this . outputStack = [ ]
8+ }
9+
10+ // Push item into the inputstack
11+ enqueue ( item ) {
12+ this . inputStack . push ( item )
13+ }
14+
15+ dequeue ( item ) {
16+ // push all items to outputstack
17+ this . outputStack = [ ]
18+ if ( this . inputStack . length > 0 ) {
19+ while ( this . inputStack . length > 0 ) {
20+ this . outputStack . push ( this . inputStack . pop ( ) )
21+ }
22+ }
23+ // display the top element of the outputstack
24+ if ( this . outputStack . length > 0 ) {
25+ console . log ( this . outputStack . pop ( ) )
26+ // repush all the items to the inputstack
27+ this . inputStack = [ ]
28+ while ( this . outputStack . length > 0 ) {
29+ this . inputStack . push ( this . outputStack . pop ( ) )
30+ }
31+ }
32+ }
33+
34+ // display elements of the inputstack
35+ listIn ( ) {
36+ let i = 0
37+ while ( i < this . inputStack . length ) {
38+ console . log ( this . inputStack [ i ] )
39+ i ++
40+ }
41+ }
42+
43+ // display element of the outputstack
44+ listOut ( ) {
45+ let i = 0
46+ while ( i < this . outputStack . length ) {
47+ console . log ( this . outputStack [ i ] )
48+ i ++
49+ }
50+ }
51+ }
52+
53+ // testing
54+
55+ const queue = new Queue ( )
56+ queue . enqueue ( 1 )
57+ queue . enqueue ( 2 )
58+ queue . enqueue ( 8 )
59+ queue . enqueue ( 9 )
60+
61+ console . log ( queue . dequeue ( ) )
62+ // ans = 1
63+ console . log ( queue . dequeue ( ) )
64+ // ans = 2
You can’t perform that action at this time.
0 commit comments