您的位置:首页 > 产品设计 > UI/UE

Leetcode_232_Implement Queue using Stacks

2015-09-12 11:01 375 查看
本文是在学习中的总结,欢迎转载但请注明出处: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 top
,
peek/pop from top
,
size
, 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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: