package Queue;
import java.util.LinkedList;
import java.util.Queue;
public class StackWithTwoQueues<T> {
public Queue<T> q1 = new LinkedList<T>();
public Queue<T> q2 = new LinkedList<T>();
public void push(T data) {
if (q1.isEmpty()) {
q1.offer(data);
} else {
q2.offer(data);
}
}
public T pop() {
int i = 0, size;
if (q2.isEmpty()) {
size = q1.size();
while (i < size - 1) {
q2.offer(q1.poll());
i++;
}
return q1.poll();
} else {
size = q2.size();
while (i < size - 1) {
q1.offer(q2.poll());
i++;
}
}
return q2.poll();
}
public void showStackData(){
while(!q1.isEmpty()){
System.out.print(q1.poll()+" ");
}
while(!q2.isEmpty()){
System.out.print(q2.poll()+" ");
}
}
public static void main(String[] args) {
StackWithTwoQueues<Integer> obj = new StackWithTwoQueues<Integer>();
obj.push(5);
obj.push(6);
obj.push(7);
obj.push(8);
//obj.showStackData();
while(obj!=null){
System.out.print(obj.pop()+" ");
}
/*System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");*/
}
}
import java.util.LinkedList;
import java.util.Queue;
public class StackWithTwoQueues<T> {
public Queue<T> q1 = new LinkedList<T>();
public Queue<T> q2 = new LinkedList<T>();
public void push(T data) {
if (q1.isEmpty()) {
q1.offer(data);
} else {
q2.offer(data);
}
}
public T pop() {
int i = 0, size;
if (q2.isEmpty()) {
size = q1.size();
while (i < size - 1) {
q2.offer(q1.poll());
i++;
}
return q1.poll();
} else {
size = q2.size();
while (i < size - 1) {
q1.offer(q2.poll());
i++;
}
}
return q2.poll();
}
public void showStackData(){
while(!q1.isEmpty()){
System.out.print(q1.poll()+" ");
}
while(!q2.isEmpty()){
System.out.print(q2.poll()+" ");
}
}
public static void main(String[] args) {
StackWithTwoQueues<Integer> obj = new StackWithTwoQueues<Integer>();
obj.push(5);
obj.push(6);
obj.push(7);
obj.push(8);
//obj.showStackData();
while(obj!=null){
System.out.print(obj.pop()+" ");
}
/*System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");
System.out.print(obj.pop()+" ");*/
}
}
No comments:
Post a Comment