java桟Stack对象

使用Stack类,Stack堆栈添加移除元素的原则是后进先出。 Stack类的主要方法是:push(),peek(),pop(),empty(),search().

说明如下 - push() - 在栈顶添加元素 - peek() - 返回栈顶的元素,但是不删除栈顶元素 - pop() - 和peek()一样返回栈顶元素,但是要将栈顶元素移除掉 - empty() - 检查栈是否为空 - search() - 返回元素在堆栈中的位置

如下示例代码:

//Create the Stack instance and add a couple of elements to itStack stack =newStack();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

猜你喜欢

转载自liuzhiqiang19890403.iteye.com/blog/2182849