栈-Stack

2021-06-07  本文已影响0人  蒋斌文

栈-Stack

image-20210607143917143

栈的接口设计

image-20210607144029149
public class Stack<E> {
   private List<E> list = new ArrayList<>();
   
   public void clear() {
      list.clear();
   }
   
   public int size() {
      return list.size();
   }

   public boolean isEmpty() {
      return list.isEmpty();
   }

   public void push(E element) {
      list.add(element);
   }


   public E pop() {
      return list.remove(list.size() - 1);
   }


   public E top() {
      return list.get(list.size() - 1);
   }
}

225. 用队列实现栈

难度简单

请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(pushtoppopempty)。

实现 MyStack 类:

注意:

public static class TwoQueueStack<T> {
   public Queue<T> queue;
   public Queue<T> help;

   public TwoQueueStack() {
      queue = new LinkedList<>();
      help = new LinkedList<>();
   }

   public void push(T value) {
      queue.offer(value);
   }

   public T poll() {
      while (queue.size() > 1) {
         help.offer(queue.poll());
      }
      T ans = queue.poll();
      Queue<T> tmp = queue;
      queue = help;
      help = tmp;
      return ans;
   }

   public T peek() {
      while (queue.size() > 1) {
         help.offer(queue.poll());
      }
      T ans = queue.poll();
      help.offer(ans);
      Queue<T> tmp = queue;
      queue = help;
      help = tmp;
      return ans;
   }

   public boolean isEmpty() {
      return queue.isEmpty();
   }

}

232. 用栈实现队列

难度简单416收藏分享切换为英文接收动态反馈

请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(pushpoppeekempty):

实现 MyQueue 类:

说明:

进阶:

class MyQueue {
    private Stack<Integer> inStack;
    private Stack<Integer> outStack;

    /** Initialize your data structure here. */
    public MyQueue() {
        inStack = new Stack<>();
        outStack = new Stack<>();
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        inStack.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        checkOutStack();
        return outStack.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        checkOutStack();
        return outStack.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return inStack.isEmpty() && outStack.isEmpty();
    }

    private void checkOutStack() {
        if (outStack.isEmpty()) {
            while (!inStack.isEmpty()) {
                outStack.push(inStack.pop());
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读