Java数据结构——栈(Stack)

栈是Vector的一个子类,它实现了一个标准的后进先出的栈
堆栈只定义了默认构造函数,用来创建一个空栈。堆栈除了包括Vector定义的所有方法,也定义了自己的一些方法。
栈构造函数

Stack()		//创建默认栈

栈的额外方法

序号方法描述
1boolean empty()测试堆栈是否为空。
2Object peek( )查看堆栈顶部的对象,但不从堆栈中移除它。
3Object pop( )移除堆栈顶部的对象,并作为此函数的值返回该对象。
4Object push(Object element)把项压入堆栈顶部。
5int search(Object element)返回对象在堆栈中的位置,以 1 为基数。

实例

import java.util.*;
 
public class StackDemo {
 
 	//压入并输出
    static void showpush(Stack<Integer> st, int a) {
        st.push(new Integer(a));
        System.out.println("push(" + a + ")");
        System.out.println("stack: " + st);
    }
 
 	//弹出并输出
    static void showpop(Stack<Integer> st) {
        System.out.print("pop -> ");
        Integer a = (Integer) st.pop();
        System.out.println(a);
        System.out.println("stack: " + st);
    }
 
    public static void main(String args[]) {
        Stack<Integer> st = new Stack<Integer>();	//创建栈对象,并实例化,栈类型为int
        System.out.println("stack: " + st);
        showpush(st, 42);
        showpush(st, 66);
        showpush(st, 99);
        showpop(st);
        showpop(st);
        showpop(st);
        try {
            showpop(st);
        } catch (EmptyStackException e) {
            System.out.println("empty stack");
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值