Implement Stack Using Queue

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;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值