Lettcode_232_Implement Queue using Stacks,lettcode

來源:互聯網
上載者:User

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



著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.