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

LeetCode_Implement Queue using Stacks_队列操作

2016-01-19 14:06 369 查看
232. Implement Queue using Stacks

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).
如题,这是使用堆中处理队列,
push(x),将元素x加入到队列末尾

pop(),从队列中移除顶端元素

peek(),得到队列顶端元素

empty(),判断队列大小是否为空

现在补充关于队列的知识,

1,定义:

队列(Queue)是只允许在一端进行插入,而在另一端进行删除的运算受限的线性表,

(1)允许删除的一端称为队头(Front)。
  (2)允许插入的一端称为队尾(Rear)。
  (3)当队列中没有元素时称为空队列。
  (4)队列亦称作先进先出(First In First Out)的线性表,简称为FIFO表。
     队列的修改是依先进先出的原则进行的。新来的成员总是加入队尾(即不允许"加塞"),每次离开的成员总是队列头上的(不允许中途离队),即当前"最老的"成员离队。

本题的题意是:

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

(2)要用栈来实现队列,首先需要了解栈和队列的性质。

栈:先进后出,只能在栈顶增加和删除元素

队列:先进先出,只能在队尾增加元素,从队头删除元素。这样,用栈实现队列,就需要对两个栈进行操作,这里需要指定其中一个栈为存储元素的栈,假定为stack2,另一个为stack1。当有元素加入时,首先判断stack2是否为空(可以认为stack2是目标队列存放元素的实体),如果不为空,则需要将stack2中的元素全部放入(辅助栈)stack1中,这样stack1中存储的第一个元素为队尾元素;然后,将待加入队列的元素加入到stack1中,这样相当于实现了将入队的元素放入队尾;最后,将stack1中的元素全部放入stack2中,这样stack2的栈顶元素就变为队列第一个元素,对队列的pop和peek的操作就可以直接通过对stack2进行操作即可。class MyQueue {
Stack<Integer> s1 = new Stack<>();
Stack<Integer> s2 = new Stack<>();
// Push element x to the back of queue.
public void push(int x) {
s1.push(x);
}
// Removes the element from in front of queue.
public void pop() {
if(!s2.isEmpty()) s2.pop();
else {
while(!s1.isEmpty()) s2.push(s1.pop());
s2.pop();
}
}

// Get the front element.
public int peek() {
if(!s2.isEmpty()) return s2.peek();
else {
while(!s1.isEmpty()) s2.push(s1.pop());
return s2.peek();
}
}

// Return whether the queue is empty.
public boolean empty() {
return s1.empty() && s2.empty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: