NOTE: If you can't use a OO approach like below, just the a queue like q, and manipulate the queue as presented below.
If you have to use a Queue, this is a decent solution, although a much better approach would be to us the Stack class, or implement a Stack using other data structures.
public class MyStack<T> {
/**
* @param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
Output:
4
3
2
1
null
Queueinterface does not specify if data is inserted at the head or the tail. Therefore, you cannot know what you really are doing on a Queue.