Home  >  Article  >  Java  >  A case study of how Java uses two stacks to implement a queue

A case study of how Java uses two stacks to implement a queue

黄舟
黄舟Original
2017-10-17 09:36:491583browse

This article mainly introduces Java programming to use two stacks to realize queue code sharing. It has certain reference value. I will share it with you here for friends who need it.

Title: Use two stacks to implement a queue and complete the Push and Pop operations of the queue. The elements in the queue are of type int.

Classic questions, not much to say, just go to the code


import java.util.Stack;
public class Solution {
  Stack<Integer> stack1 = new Stack<Integer>();
  Stack<Integer> stack2 = new Stack<Integer>();
  public void push(int node) {
    stack1.push(node);
  }
  public int pop() {
    while(!stack1.isEmpty()){
      stack2.push(stack1.pop());
    }
    int pop = stack2.pop();
    while(!stack2.isEmpty()){
      stack1.push(stack2.pop());
    }
    return pop;
  }
}

Summary

The above is the detailed content of A case study of how Java uses two stacks to implement a queue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn