用棧實現佇列-leetcode
題目描述
使用棧實現佇列的下列操作:
push(x) -- 將一個元素放入佇列的尾部。
pop() -- 從佇列首部移除元素。
peek() -- 返回佇列首部的元素。
empty() -- 返回佇列是否為空。
棧:先進後出;
佇列:先進先出;
思路:
1.使用兩個棧stack 、queue ;
2.將資料push到stack中;
3.queue 進行出隊,則是stack中出棧,如果queue無資料則stack就行出棧,如果queue 有資料就進行出棧;
Stack<int> stack = new Stack<int>(); Stack<int> queue = new Stack<int>(); public MyQueue() { } public void Push(int x) { stack.push(x); } public int Pop() { if (queue.isEmpty()) { while (stack.top != null) { queue.push(stack.peek()); stack.pop(); } } int topV = queue.peek(); queue.pop(); return topV; } /** Get the front element. */ public int Peek() { if (queue.isEmpty()) { while (stack.top != null) { queue.push(stack.peek()); stack.pop(); } } return queue.peek(); } /** Returns whether the queue is empty. */ public bool Empty() { if (queue.isEmpty()) { while (stack.top != null) { queue.push(stack.peek()); stack.pop(); } } if (queue.top == null) return false; return true; }