DailyChallenge

Offer 09. Implement queues with two stacks

Easy20200630

Description

Implement a queue with two stacks. Implement appendTail and deleteHead to insert an integer at the end of the queue and delete an integer at the head of the queue. (If there are no elements in the queue, the deleteHead operation returns -1)

The sample1:
Input:["CQueue"."appendTail"."deleteHead"."deleteHead"]
[[], [3], [], []]Output: [null, null,3.- 1]  The sample2: Input:["CQueue"."deleteHead"."appendTail"."appendTail"."deleteHead"."deleteHead"] [[], [], [5], [2], [], []]Output: [null,- 1,null,null,5.2] Copy the code

Tip:

  • 1 <= values <= 10000
  • At most 10000 calls are made to appendTail and deleteHead

Links:

Leetcode-cn.com/problems/yo…

Solution

Notice that you don’t want to use a stack, you want to use a deque.

class CQueue {
    Deque<Integer> stack1;
    Deque<Integer> stack2;

    public CQueue(a) {
 stack1 = new LinkedList<>();  stack2 = new LinkedList<>();  }   public void appendTail(int value) {  stack1.add(value);   }   public int deleteHead(a) {  if(stack2.isEmpty()){  while(! stack1.isEmpty()){ stack2.add(stack1.pop());  }  }  return stack2.isEmpty()? -1 : stack2.pop();  } }  / * * * Your CQueue object will be instantiated and called as such:  * CQueue obj = new CQueue();  * obj.appendTail(value);  * int param_2 = obj.deleteHead(); * / Copy the code

My official account is GitKid

Temporarily share LeetCode every day, I am in the process of continuous learning, the public account is also constantly enriched, welcome everyone to scan code attention.

TODO: Sorting topics

Wechat official account

This article is formatted using MDNICE