File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .*; //Through this we import all need packages in the code
2
+
3
+ public class Solution {
4
+ //here we require 2 queue, for enqueue and dequeue
5
+ Queue <Integer > queue1 = new LinkedList <Integer >();
6
+ Queue <Integer > queue2 = new LinkedList <Integer >();
7
+ int size = 0 ; //initial size is 0
8
+
9
+ //Push function
10
+ public void push (int data ){ //here in data we share the number from the main function in queue 2
11
+ queue2 .add (data ); //added the number to queue 2
12
+ size ++; //size increases
13
+ while (!queue1 .isEmpty ()){
14
+ queue2 .add (queue1 .remove ()); //return value is added to queue 2
15
+ }
16
+ //here we swap the numbers
17
+ Queue <Integer > temp = queue1 ;
18
+ queue1 = queue2 ;
19
+ queue2 = temp ;
20
+ }
21
+
22
+ //Pop function
23
+ public int pop () throws Exception { //used custom exception to throw our exception
24
+ if (queue1 .isEmpty ()){
25
+ throw new Exception ("The stack have null elements" );
26
+ }
27
+ size --; //size gets decreases
28
+ return queue1 .remove ();
29
+ }
30
+ public static void main (String [] args ) throws Exception {
31
+
32
+ Solution obj = new Solution ();
33
+ //push the numbers to data
34
+ obj .push (12 );
35
+ obj .push (67 );
36
+ obj .push (34 );
37
+ obj .push (89 );
38
+ obj .push (21 );
39
+
40
+ System .out .println ("Removed Element: " +obj .pop ());
41
+ System .out .println ("Removed Element: " +obj .pop ());
42
+ System .out .println ("Removed Element: " +obj .pop ());
43
+ System .out .println ("Removed Element: " +obj .pop ());
44
+ System .out .println ("Removed Element: " +obj .pop ());
45
+ }
46
+ }
You can’t perform that action at this time.
0 commit comments