用两个栈实现队列
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台


- class CQueue {
- Stack
in=new Stack<>(); - Stack
out=new Stack<>(); - public CQueue() {
- Stack
in=new Stack<>(); - Stack
out=new Stack<>(); - }
-
- public void appendTail(int value) {
- while(!out.isEmpty())
- {
- int num=out.pop();
- in.push(num);
- }
- in.push(value);
- }
-
- public int deleteHead() {
- while(!in.isEmpty())
- {
- int num=in.pop();
- out.push(num);
- }
- if(out.isEmpty())return -1;
- return out.pop();
- }
- }
用队列实现栈
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

- class MyStack {
-
- LinkedList
list=new LinkedList<>(); - public MyStack() {
- LinkedList
list=new LinkedList<>(); - }
-
- public void push(int x) {
- list.push(x);
- }
-
- public int pop() {
- return list.pop();
- }
-
- public int top() {
- return list.peek();
- }
-
- public boolean empty() {
- return list.isEmpty();
- }
- }
力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

- class MyQueue {
- Stack
in=new Stack<>(); - Stack
out=new Stack<>(); - public MyQueue() {
- Stack
in=new Stack<>(); - Stack
out=new Stack<>(); - }
-
- public void push(int x) {
- while(!out.isEmpty())
- {
- int num=out.pop();
- in.push(num);
- }
- in.push(x);
- }
-
- public int pop() {
- while(!in.isEmpty())
- {
- int num=in.pop();
- out.push(num);
- }
- if(out.isEmpty())return -1;
- return out.pop();
- }
-
- public int peek() {
- while(!in.isEmpty())
- {
- int num=in.pop();
- out.push(num);
- }
- if(out.isEmpty())return -1;
- return out.peek();
- }
-
- public boolean empty() {
- if(in.isEmpty()&&out.isEmpty())return true;
- return false;
- }
- }