import java.util.LinkedList;
import java.util.Queue;
public class Stack {
Queue<Integer> Q1,Q2;
public Stack() {
Q1=new LinkedList<Integer>();
Q2=new LinkedList<Integer>();
}
public void push(int data) {
Q1.add(data);
}
public int peek() {
int size=Q1.size()-1;
for(int i=0; i<size;i++)
Q2.add(Q1.remove());
int peek = Q1.remove();
Q2.add(peek);
SwapQueues();
return peek;
}
public int pop() {
int size=Q1.size()-1;
for(int i=0; i<size;i++)
Q2.add(Q1.remove());
int pop = Q1.remove();
SwapQueues();
return pop;
}
private void SwapQueues() {
Queue<Integer> temp = Q1;
Q1=Q2;
Q2=temp;
}
}
Showing posts with label Queue. Show all posts
Showing posts with label Queue. Show all posts
Wednesday, December 2, 2015
Queue Implementation using Two Stacks
import java.util.Stack;
public class Queue {
Stack<Integer> S1;
Stack<Integer> S2;
public Queue() {
S1 = new Stack<Integer>();
S2 = new Stack<Integer>();
}
public void enqueue(int data) {
S1.push(data);
}
private void ShiftS1toS2() {
while(!S1.isEmpty())
S2.push(S1.pop());
}
public int dequeue() {
ShiftS1toS2();
return S2.pop();
}
public int lookup() {
ShiftS1toS2();
return S2.peek();
}
}
public class Queue {
Stack<Integer> S1;
Stack<Integer> S2;
public Queue() {
S1 = new Stack<Integer>();
S2 = new Stack<Integer>();
}
public void enqueue(int data) {
S1.push(data);
}
private void ShiftS1toS2() {
while(!S1.isEmpty())
S2.push(S1.pop());
}
public int dequeue() {
ShiftS1toS2();
return S2.pop();
}
public int lookup() {
ShiftS1toS2();
return S2.peek();
}
}
Labels:
Algorithm,
Data Structures,
Java,
Jeevan,
Jeevan Rex,
Jeevanus,
Queue,
Stack
Subscribe to:
Posts (Atom)