admin管理员组

文章数量:1636990

We are given a Queue data structure that supports standard operations like enqueue() and dequeue(). We need to implement a Stack data structure using only instances of Queue

this question is from GeeksforGeeks 

Implement Stack Question from geeksforgeeks

此问题和 Implement Queue use Stack 一样

两种方法实现:

1 update on each push operation  

push(s, x) // x is the element to be pushed and s is stack
1) Enqueue x to q2
2) One by one dequeue everything from q1 and enqueue to q2.
3) Swap the names of q1 and q2
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1.

pop(s)
1) Dequeue an item from q1 and return it.















2 Update when pop --很好理解,就是把queue1中除了最后一个都存到queue2中,poll出queue1中最后一个就是latest element,交换名字

In push operation, the new element is always enqueued to q1.
In pop() operation, if q2 is empty then all the elements except the last, are moved to q2.
Finally the last element is dequeued from q1 and returned.

push(s, x)
1) Enqueue x to q1 (assuming size of q1 is unlimited).

pop(s)
1) One by one dequeue everything except the last element from q1 and enqueue to q2.
2) Dequeue the last item of q1, the dequeued item is result, store it.
3) Swap the names of q1 and q2
4) Return the item stored in step 2.
// Swapping of names is done to avoid one more movement of all elements  from q2 to q1.

private Queue<Integer> queue1;
	private Queue<Integer> queue2;
    
    public ImplementStackusingQueues() {
       // do initialization if necessary
       queue1 = new LinkedList<Integer>();
       queue2 = new LinkedList<Integer>();
  
    }
    public void push(int element){
    	queue1.offer(element);
    }
    public int pop(){
    	while(queue1.size() > 1){
    		queue2.offer(queue1.poll());
    	}
    	//remain last element
    	int top = queue1.poll();
    	queue1 = queue2;
    	queue2 = queue1;
    	return top;
    }



本文标签: implementStackQueue