Dequeue efficient queue using stack

public static int dequeue(){
primary.pop();
}
public static void enqueue(int data){
while(primary.size()!==0){
secondary.push(primary.pop());
}
primary.push(data);
while(secondary.size()!==0){
primary.push(secondary.pop());
}
public static void main(String args[]) {
try
{ Stack primary=new Stack<>();
Stack secondary=new Stack<>();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();

	for(int i=0;i<n;i++){
		primary.enqueue(i);
	}
	for(int i=0;i<n;i++){
		System.out.primary(primary.dequeue();}}
		catch(Exception e){System.out.println(e);}

I am using predefine stack in this question but it is showing not correct ,can you plz tell me why

@Sweta,
Your logic is correct. There are many syntax mistakes. https://ide.geeksforgeeks.org/ms1ljUgWcf I have corrected your code. Please understand the changes. You cannot use enqueue and dequeue as stack methods.

1 Like

@Sweta,
See the predefined stack class has some methods and you cannot add enqueue and dequeue to it. It will give you an error. What I did is, I made the primary and secondary stacks global and static and instead of doing this: primary.enqueue(i); you can just call the enqueue method and it will push the element. Same goes for dequeue.

Just understand that with predefined stack class, this is not valid: primary.dequeue();

Pre defined stack class in java has the following methods and you cannot modify it:
Methods in Stack class

  1. Object push(Object element) : Pushes an element on the top of the stack.
  2. Object pop() : Removes and returns the top element of the stack. An ‘EmptyStackException’ exception is thrown if we call pop() when the invoking stack is empty.
  3. Object peek() : Returns the element on the top of the stack, but does not remove it.
  4. boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false.
  5. int search(Object element) : It determines whether an object exists in the stack. If the element is found, it returns the position of the element from the top of the stack. Else, it returns -1.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.