Stack

Stack

  • public class Stack<E>   extends Vector<E>

Stack是Vector的子类,是一个标准的先进后出的栈。

Stack有几个自己特有的方法。

Modifier and TypeMethod and Description
booleanempty()
Tests if this stack is empty.
Epeek()
Looks at the object at the top of this stack without removing it from the stack.
Epop()
Removes the object at the top of this stack and returns that object as the value of this function.
Epush(E item)
Pushes an item onto the top of this stack.
intsearch(Object o)
Returns the 1-based position where an object is on this stack.
1. empty()方法,判断stack是否为空,返回值为boolean类型。

2.peek()方法,返回stack栈顶的元素,如果栈为空,则报错栈为空。

3.pop()方法,取出栈顶的元素,并且返回该元素。

4.push()方法,将当前元素压入栈中,int型,string型,char型均可。

5.search()方法,寻找目标第一个出现的位置距离栈顶的距离,不存在的话返回值为-1。


代码实现:

import java.util.Stack;
public class Test {
    public static void main(String[] args){
        Stack stack=new Stack();
        System.out.println("stack为空吗:"+stack.empty());
        stack.push(1);
        System.out.println("放进一个元素后stack为空吗:"+stack.empty());
        stack.push('1');
        stack.push("1");
        stack.push("aa");
        System.out.println("栈顶元素:"+stack.peek());
        System.out.println("11的位置"+stack.search("11"));
        System.out.println("aa的位置"+stack.search("aa"));
        System.out.println("string型1的位置"+stack.search("1"));
        System.out.println("字符型1的位置"+stack.search('1'));
        System.out.println("整形1的位置"+stack.search(1));
        System.out.println("拿出了"+stack.pop());
        System.out.println("拿出了"+stack.pop());
        System.out.println("拿出了"+stack.pop());
        System.out.println("拿出了"+stack.pop());
        System.out.println("stack为空吗:"+stack.empty());
    }
}

运行结果:

stack为空吗:true
放进一个元素后stack为空吗:false
栈顶元素:aa
11的位置-1
aa的位置1
string型1的位置2
字符型1的位置3
整形1的位置4
拿出了aa
拿出了1
拿出了1
拿出了1
stack为空吗:true



  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值