1. 程式人生 > 其它 >力扣簡225 用佇列實現棧++

力扣簡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處調整,把另一個佇列的排放直接變成棧。

題解二是隻使用一個佇列。當放入新元素時,把之前放入的已經是棧排列的元素依次出棧並重新加入