Stack

Stack

  • public class Stack   extends Vector

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

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

Modifier and Type Method and Description
boolean empty()
Tests if this stack is empty.
E peek()
Looks at the object at the top of this stack without removing it from the stack.
E pop()
Removes the object at the top of this stack and returns that object as the value of this function.
E push(E item)
Pushes an item onto the top of this stack.
int search(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



你可能感兴趣的:(Java)