栈和队列的实现Java

栈和队列

 

 

栈的实现

tt指向栈顶,tt初始值为0

 

 

队列实现

hh为队头,tt为队尾,tt初始值为负一,在队尾插入元素,在队头弹出元素

 

 

 

 

 1 import java.util.*;
 2 public class Main{
 3     static int stk[]=new int[100010];
 4     static int tt=0;//栈顶
 5     //弹出
 6     public static void pop(){
 7         tt--;
 8     }
 9     //入栈
10     public static void push(int x){
11         stk[++tt]=x;
12     }
13     //判断栈是否为空
14     public static String empty(){
15         if(tt==0){
16             return "YES";
17         }
18         return "NO";
19     }
20     //查询栈顶元素
21     public static int query(){
22         return stk[tt];
23     }
24     public static void main(String[] args){
25         Scanner scan=new Scanner(System.in);
26         int m=scan.nextInt();
27         while(m-->0){
28             String s=scan.next();
29             if(s.equals("push")){
30                 int x=scan.nextInt();
31                 push(x);
32             }
33             else if(s.equals("pop")){
34                 pop();
35             }
36             else if(s.equals("empty")){
37                 System.out.println(empty());
38             }
39             else{
40                 System.out.println(query());
41             }
42         }
43     }
44 }

 

 

 1 import java.util.*;
 2 public class Main{
 3     static int q[]=new int[100010];
 4     static int tt=-1;//队尾
 5     static int hh=0;//队首
 6     //出队
 7     public static void pop(){
 8         hh++;
 9     }
10     //入队
11     public static void push(int x){
12         q[++tt]=x;
13     }
14     //判断队是否为空
15     public static String empty(){
16         if(hh<=tt){
17             return "NO";
18         }
19         return "YES";
20     }
21     //查询队顶元素
22     public static int query(){
23         return q[hh];
24     }
25     public static void main(String[] args){
26         Scanner scan=new Scanner(System.in);
27         int m=scan.nextInt();
28         while(m-->0){
29             String s=scan.next();
30             if(s.equals("push")){
31                 int x=scan.nextInt();
32                 push(x);
33             }
34             else if(s.equals("pop")){
35                 pop();
36             }
37             else if(s.equals("empty")){
38                 System.out.println(empty());
39             }
40             else{
41                 System.out.println(query());
42             }
43         }
44     }
45 }

 

posted @ 2022-04-06 18:33  经典的错误  阅读(47)  评论(0)    收藏  举报