File tree Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Expand file tree Collapse file tree 2 files changed +71
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .io .BufferedReader ;
2
+ import java .io .IOException ;
3
+ import java .io .InputStreamReader ;
4
+ import java .util .Arrays ;
5
+ import java .util .Stack ;
6
+
7
+ class Queue <T >{
8
+ Stack <T > inStack ;
9
+ Stack <T > outStack ;
10
+
11
+ public Queue () {
12
+ this .inStack = new Stack <>();
13
+ this .outStack = new Stack <>();
14
+ }
15
+
16
+ public void offer (T obj ){
17
+ this .outStack .push ( obj );
18
+ }
19
+
20
+ public T poll (){
21
+ while (!outStack .isEmpty ()) {
22
+ inStack .push (outStack .pop ());
23
+ }
24
+ T number = inStack .pop ();
25
+ while (!inStack .isEmpty ()) {
26
+ outStack .push ( inStack .pop () );
27
+ }
28
+ return number ;
29
+ }
30
+
31
+ public boolean isEmpty (){
32
+ return outStack .isEmpty ();
33
+ }
34
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .LinkedList ;
2
+ import java .util .Queue ;
3
+
4
+ public class Stack <T > {
5
+
6
+ Queue <T > inQueue ;
7
+ Queue <T > outQueue ;
8
+
9
+ public Stack (){
10
+ this .inQueue = new LinkedList <>();
11
+ this .outQueue = new LinkedList <>();
12
+ }
13
+
14
+ public void push (T obj ){
15
+ this .outQueue .offer ( obj );
16
+ }
17
+
18
+ public T pop (){
19
+ while ( outQueue .size () != 1 ){
20
+ inQueue .offer ( outQueue .poll () );
21
+ }
22
+ T poll = outQueue .poll ();
23
+ while ( !inQueue .isEmpty () ){
24
+ outQueue .offer ( inQueue .poll () );
25
+ }
26
+ return poll ;
27
+ }
28
+
29
+ public boolean isEmpty (){
30
+ return outQueue .isEmpty ();
31
+ }
32
+
33
+ public int size (){
34
+ return outQueue .size ();
35
+ }
36
+
37
+ }
You can’t perform that action at this time.
0 commit comments