Leetcode_232_Implement Queue using Stacks

97 篇文章 0 订阅
94 篇文章 18 订阅

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/48392363


Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).



思路:

(1)题意为用栈来实现队列。

(2)要用栈来实现队列,首先需要了解栈和队列的性质。栈:先进后出,只能在栈顶增加和删除元素;队列:先进先出,只能在队尾增加元素,从队头删除元素。这样,用栈实现队列,就需要对两个栈进行操作,这里需要指定其中一个栈为存储元素的栈,假定为stack2,另一个为stack1。当有元素加入时,首先判断stack2是否为空(可以认为stack2是目标队列存放元素的实体),如果不为空,则需要将stack2中的元素全部放入(辅助栈)stack1中,这样stack1中存储的第一个元素为队尾元素;然后,将待加入队列的元素加入到stack1中,这样相当于实现了将入队的元素放入队尾;最后,将stack1中的元素全部放入stack2中,这样stack2的栈顶元素就变为队列第一个元素,对队列的pop和peek的操作就可以直接通过对stack2进行操作即可。

(3)详情见下方代码。希望本文对你有所帮助。


算法代码实现如下:

package leetcode;

import java.util.Stack;

/**
 * @author liqqc
 *
 */
public class Implement_Queue_using_Stacks {

	public Stack<Integer> _stack1 = new Stack<Integer>();
	public Stack<Integer> _stack2 = new Stack<Integer>();

	public void push(int x) {
		while (!_stack2.isEmpty()) {
			_stack1.push(_stack2.pop());
		}
		_stack1.push(x);
		while (!_stack1.isEmpty()) {
			_stack2.push(_stack1.pop());
		}

	}

	// Removes the element from in front of queue.
	public void pop() {
		_stack2.pop();
	}

	// Get the front element.
	public int peek() {
		return _stack2.peek();
	}

	// Return whether the queue is empty.
	public boolean empty() {
		return _stack2.isEmpty();
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值