File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
src/main/java/com/ctci/stacksandqueues Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .ctci .stacksandqueues ;
2+
3+ import java .util .NoSuchElementException ;
4+ import java .util .Stack ;
5+
6+ /**
7+ * @author rampatra
8+ * @since 2019-02-06
9+ */
10+ public class QueueViaStacks <T > {
11+
12+ private Stack <T > stackFront = new Stack <>();
13+ private Stack <T > stackRear = new Stack <>();
14+
15+ private T add (T item ) {
16+ return stackRear .push (item );
17+ }
18+
19+ private T remove () {
20+ if (stackFront .empty () && stackRear .empty ()) {
21+ throw new NoSuchElementException ();
22+ } else if (!stackFront .empty ()) {
23+ return stackFront .pop ();
24+ } else {
25+ while (!stackRear .empty ()) {
26+ stackFront .push (stackRear .pop ());
27+ }
28+ return stackFront .pop ();
29+ }
30+ }
31+
32+ private void print () {
33+ Stack <T > tempStack = new Stack <>();
34+ while (!stackFront .empty ()) {
35+ tempStack .push (stackFront .pop ());
36+ }
37+ System .out .print ("[" );
38+ tempStack .forEach (item -> System .out .print (item + "," ));
39+ stackRear .forEach (item -> System .out .print (item + "," ));
40+ System .out .println ("]" );
41+ while (!tempStack .empty ()) {
42+ stackFront .push (tempStack .pop ());
43+ }
44+ }
45+
46+ public static void main (String [] args ) {
47+ QueueViaStacks <Integer > queue = new QueueViaStacks <>();
48+ queue .add (1 );
49+ queue .add (2 );
50+ queue .add (3 );
51+ queue .print ();
52+ queue .remove ();
53+ queue .print ();
54+ queue .remove ();
55+ queue .print ();
56+ queue .remove ();
57+ queue .print ();
58+ }
59+ }
You can’t perform that action at this time.
0 commit comments