力扣简225 用队列实现栈++ 看题解

和题解不太一样,需要重新敲一下

 

隔了一天,本来昨天写的,没运行也没改,今天写还不如重新开始!

自己还把static给删了 导致一直都运行不了 还把变量台删了 找了好半天 我真是迷迷糊糊

 1 package leetcode01;
 2 
 3 import java.util.LinkedList;
 4 import java.util.List;
 5 import java.util.Queue;
 6 
 7 import javax.swing.border.EmptyBorder;
 8 
 9 class MyStack {
10     
11     Queue<Integer> queue1;
12     Queue<Integer> queue2;
13 
14     public MyStack() {
15         queue1=new LinkedList<Integer>();
16         queue2=new LinkedList<Integer>();
17         
18     }
19     
20     public void push(int x) {
21         if(!queue2.isEmpty()) {
22             queue2.add(x);
23         }
24         else {
25             queue1.add(x);
26         }
27         
28     }
29     
30     public int pop() {
31         while(!queue1.isEmpty()) {
32             int a=queue1.poll();
33             if(!queue1.isEmpty()) {
34                 queue2.add(a);
35             }
36             else {
37                 return a;
38             }
39         }   
40         while(!queue2.isEmpty()) {
41             int a=queue2.poll();
42             if(!queue2.isEmpty()) {
43                 queue1.add(a);
44             }
45             else {
46                 return a;
47             }
48         }
49         return 0;
50     }
51     
52     public int top() {
53         while(!queue1.isEmpty()) {
54             int a=queue1.poll();
55             queue2.add(a);
56             if(queue1.isEmpty())
57                 return a;
58         }
59         while(!queue2.isEmpty()) {
60             int a=queue2.poll();
61             queue1.add(a);
62             if(queue2.isEmpty()) 
63                 return a;
64         }
65         return 0;
66     }
67     
68     public boolean empty() {
69         if(queue1.isEmpty() && queue2.isEmpty()) {
70             return true;
71         }
72         return false;
73     }
74 }
75 
76 public class Solution225 {    
77 
78     public static void main(String[] args) {  //不能瞎改 把这个static去掉 一直都执行不进来
79         // TODO Auto-generated method stub
80         MyStack stack=new MyStack();
81         stack.push(1);
82         int b=stack.top();
83         System.out.println(b);
84         stack.push(2);
85         int c=stack.top();
86         System.out.println(c);
87         int a=stack.pop();
88         System.out.println(a);
89         int d=stack.top();
90         System.out.println(d);
91         boolean flag=stack.empty();
92         System.out.println(flag);
93     }
94 
95 }

 

 

题解一是直接用辅助队列在push处调整,把另一个队列的排放直接变成栈。

题解二是只使用一个队列。当放入新元素时,把之前放入的已经是栈排列的元素依次出栈并重新加入

posted @ 2022-06-01 11:05  Ssshiny  阅读(25)  评论(0)    收藏  举报