public class Stack<E>extends Vector<E>
Stack 类表示后进先出(LIFO)的对象堆栈。它通过五个操作对类 Vector 进行了扩展 ,允许将向量视为堆栈。它提供了通常的 push 和 pop 操作,以及取堆栈顶点的 peek 方法、测试堆栈是否为空的 empty 方法、在堆栈中查找项并确定到堆栈顶距离的 search 方法。

 方法 使用说明
boolean empty() 测试堆栈是否为空
E peek() 查看堆栈顶部的对象,但不从堆栈移除
E push(E item) 移除堆栈顶部的对象,并返回该对象
int search(Object o) 返回对象在堆栈的位置,以1为基数 

 下面是使用的例子

public class JavaStack {
    public static void main(String[] args) {
        Stack stack = new Stack(); 
        stack.push(new Integer(100)); 
        printStack(stack);  

        stack.push("thisstring"); 
        printStack(stack);

        stack.push(new Double(190.3));
        printStack(stack);  

        stack.push("secondstring");
        printStack(stack);
           
        System.out.println("元素thisstring在堆栈的位置:"+stack.search("thisstring"));

        System.out.println("顶元素"+stack.pop()+"出栈");
        printStack(stack);  //显示栈中的所有元素

 
    }

    private static void printStack(Stack<Integer> stack ){
        if (stack.empty())
            System.out.println("堆栈是空的,没有元素");
            else 
            {
                System.out.print("堆栈中的元素:");
                Enumeration items = stack.elements();  
                while (items.hasMoreElements())
                    System.out.print(items.nextElement()+" ");
            }
        System.out.println(); 
    }
}

 

相关文章:

  • 2021-12-17
  • 2022-02-07
  • 2021-06-12
  • 2022-02-07
  • 2022-12-23
  • 2021-11-07
猜你喜欢
  • 2021-09-21
  • 2021-06-18
  • 2021-12-11
  • 2022-12-23
  • 2022-02-23
  • 2022-12-23
  • 2021-11-18
相关资源
相似解决方案