Java数据结构(栈)

xiaoxiao2021-02-28  115

(想知道更详细有关Scanner的可以去查Java帮助文档) Stack类的基本方法概述: 方法摘要 booleanempty()           测试堆栈是否为空。 Epeek()           查看堆栈顶部的对象,但不从堆栈中移除它。 Epop()           移除堆栈顶部的对象,并作为此函数的值返回该对象。 Epush(E item)           把项压入堆栈顶部。 intsearch(Object o)           返回对象在堆栈中的位置,以 1 为基数。

import java.util.*; import java.util.Scanner; public class StackDemo {       public static void main(String args[]) {   Stack1 sd=new Stack1();   //创建一个栈       Stack<Integer> st = new Stack<Integer>();       System.out.println("stack: " + st);       System.out.println("将n个数压入此栈");       Scanner sc=new Scanner(System.in);       int n=sc.nextInt();       System.out.println("将"+n+"个数压入此栈");       //入栈的数据       for (int i=0;i<n;i++){           int a=sc.nextInt();           sd.showpush(st, a);       }       sc.close();       //出栈       for (int i=0;i<n;i++){           sd.showpop(st);       }       try {          sd.showpop(st);       } catch (EmptyStackException e) {          System.out.println("empty stack");       }    } } class Stack1{ public void showpush(Stack<Integer>  st, int a) {      st.push(new Integer(a)); //入栈      System.out.println("push(" + a + ")");      System.out.println("stack: " + st);   }   public void showpop(Stack<Integer>  st) {      System.out.print("pop -> "); //出栈      Integer a = (Integer) st.pop();//注意:int和integer的区别,int为基本数据类型,integer为int的封装类      System.out.println(a);      System.out.println("stack: " + st);   } }
转载请注明原文地址: https://www.6miu.com/read-26156.html

最新回复(0)