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

Question 6

Programming

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)
23 views2 pages

Question 6

Programming

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
You are on page 1/ 2

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 java.util.LinkedList;
import java.util.Queue;

/**
*
* @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


q2.add(x);

// Push all the remaining


// elements in q1 to q2.
while (!q1.isEmpty()) {
q2.add(q1.peek());
q1.remove();
}

// swap the names of two queues


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

void pop()
{

// if no elements are there in q1


if (q1.isEmpty())
return;
q1.remove();
curr_size--;
}

int top()
{
if (q1.isEmpty())
return -1;
return q1.peek();
}

int size()
{
return curr_size;
}

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

System.out.println("current size: " + s.size());


System.out.println(s.top());
s.pop();
System.out.println(s.top());
s.pop();
System.out.println(s.top());

System.out.println("current size: " + s.size());


}
}

You might also like