File tree 1 file changed +56
-0
lines changed
src/com/hackerrank/tutorials/ctci
1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .hackerrank .tutorials .ctci ;
2
+
3
+ import java .util .Scanner ;
4
+ import java .util .Stack ;
5
+
6
+ /**
7
+ * Question: https://www.hackerrank.com/challenges/ctci-queue-using-two-stacks
8
+ * Level: Medium
9
+ *
10
+ * @author ramswaroop
11
+ * @version 07/10/2016
12
+ */
13
+ public class QueuesWithTwoStacks {
14
+
15
+ public static class MyQueue <T > {
16
+ Stack <T > stackNewestOnTop = new Stack <T >();
17
+ Stack <T > stackOldestOnTop = new Stack <T >();
18
+
19
+ public void enqueue (T value ) { // Push onto newest stack
20
+ stackNewestOnTop .push (value );
21
+ }
22
+
23
+ public T peek () {
24
+ return stackOldestOnTop .isEmpty () ? stackNewestOnTop .firstElement () : stackOldestOnTop .peek ();
25
+ }
26
+
27
+ public T dequeue () {
28
+ if (stackOldestOnTop .isEmpty ()) {
29
+ while (!stackNewestOnTop .isEmpty ()) {
30
+ stackOldestOnTop .push (stackNewestOnTop .pop ());
31
+ }
32
+ }
33
+ return stackOldestOnTop .pop ();
34
+ }
35
+ }
36
+
37
+
38
+ public static void main (String [] args ) {
39
+ MyQueue <Integer > queue = new MyQueue <>();
40
+
41
+ Scanner scan = new Scanner (System .in );
42
+ int n = scan .nextInt ();
43
+
44
+ for (int i = 0 ; i < n ; i ++) {
45
+ int operation = scan .nextInt ();
46
+ if (operation == 1 ) { // enqueue
47
+ queue .enqueue (scan .nextInt ());
48
+ } else if (operation == 2 ) { // dequeue
49
+ queue .dequeue ();
50
+ } else if (operation == 3 ) { // print/peek
51
+ System .out .println (queue .peek ());
52
+ }
53
+ }
54
+ scan .close ();
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments