堆栈--Stack类学习
最近学习数据结构的时候,用java实现了一下堆栈,就是用stack这个类,在这里记录一下学习过程。
Class Stack<E>
Method Summary
|
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.
|
另外还继承了java.util.Vector<E>中的基本方法,常见的用法如下所示:
import java.util.*;
public class kkk{
public static void main(String args[]){
int m = 1;
Stack<Integer> a = new Stack<Integer>();
a.push(m); //压入1
a.push(m+1); //压入2
a.push(m+2); //压入3
a.push(m+3); //压入4
a.push(m+4); //压入5
System.out.println(a.push(m+5)); //压入6,并返回当前值
System.out.println(a.empty()); //判断栈是否为空,为空则TRUE
System.out.println(a.isEmpty()); //判断栈是否为空,为空则TRUE
System.out.println(a.size()); //返回当前栈长度
System.out.println(a.toString()); //返回当前栈的内容
System.out.println(a.lastElement()); //返回当前栈中的最后一个元素6
System.out.println(a.firstElement()); //返回当前栈中的第一个元素1
System.out.println(a.peek()); //返回当前值6
System.out.println(a.pop()); //返回当前值并压出6
System.out.println(a.pop()); //返回当前值并压出5
System.out.println(a.search(3));
//搜索“3”在栈中出现的位置,顶端为1,其余依次累加,若有多个则返回第1个的位置
a.add(m+9); //压入10,跟push一样的效果
a.clear(); //清空栈
System.out.println(a.empty()); //判断栈是否为空,为空则TRUE
System.out.println(a.isEmpty()); //判断栈是否为空,为空则TRUE
}
}