Lettcode_232_Implement Queue using Stacks,lettcode
本文是在學習中的總結,歡迎轉載但請註明出處: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();}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。