Stack 栈类的使用

来源:互联网 发布:linux 命令 ls l 编辑:程序博客网 时间:2024/06/08 02:52

如下示例代码

//Create the Stack instance and add a couple of elements to itStack stack = new Stack();String s1 = "element 1";String s2 = "element 2";stack.push(s1);stack.push(s2);

现在栈中有两个元素,栈顶应该是element 2,我们可以通过peek方法看栈顶的元素:

System.out.println(stack.peek());

输出:

element 2

要看element 1的位置需要使用search方法:

//Find position of a certain elementint pos = stack.search("element 1");System.out.println(pos);

上面代码将输出:

2

要移除栈顶的元素应该用pop()方法:

System.out.println(stack.pop());System.out.println(stack.pop());

输出:

element 2
element 1

在上一步中栈中的两个元素都被pop了,现在我们看下empty()方法是否返回true

System.out.println(stack.empty());

输出:

true

0 0
原创粉丝点击