0% found this document useful (0 votes)
3 views2 pages

Efficient Stack with Two Queues

The document presents a Java implementation of a stack using two queues, focusing on making the pop operation efficient. It includes methods for pushing elements onto the stack, popping elements off, retrieving the top element, and checking the size of the stack. The main method demonstrates the functionality of the stack implementation with sample operations.

Uploaded by

Nischal ND
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Efficient Stack with Two Queues

The document presents a Java implementation of a stack using two queues, focusing on making the pop operation efficient. It includes methods for pushing elements onto the stack, popping elements off, retrieving the top element, and checking the size of the stack. The main method demonstrates the functionality of the stack implementation with sample operations.

Uploaded by

Nischal ND
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

6) 5) Implement Stack using Two Queues which is pop() efficient

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package question6;

import [Link];
import [Link];

/**
*
* @author Nischal
*/
public class Question6 {

// Two inbuilt queues


Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();

// To maintain current number of


// elements
int curr_size;

Question6()
{
curr_size = 0;
}

void push(int x)
{
curr_size++;

// Push x first in empty q2


[Link](x);

// Push all the remaining


// elements in q1 to q2.
while (![Link]()) {
[Link]([Link]());
[Link]();
}

// swap the names of two queues


Queue<Integer> q = q1;
q1 = q2;
q2 = q;
}

void pop()
{

// if no elements are there in q1


if ([Link]())
return;
[Link]();
curr_size--;
}

int top()
{
if ([Link]())
return -1;
return [Link]();
}

int size()
{
return curr_size;
}

// driver code
public static void main(String[] args)
{
Question6 s = new Question6();
[Link](1);
[Link](2);
[Link](3);

[Link]("current size: " + [Link]());


[Link]([Link]());
[Link]();
[Link]([Link]());
[Link]();
[Link]([Link]());

[Link]("current size: " + [Link]());


}
}

You might also like