栈的特点是:先进后出,后进先出,只能从栈顶对栈进行操作。以前是使用数组的形式来实现的,使用数组麻烦的地方在于如果数组的长度越界了,那么就需要扩容,要不然就会抛出异常。今天使用系统提供的集合来实现栈。代码如下
首先定义一个接口:
public interface MyVector<E>{
//栈是否为空
boolean isEmpty();
//获取栈顶的元素
E peek();
//获取栈的元素
E pop();
//入栈
E push(E item);
//查找元素的位置
int search(Object o);
//栈的大小
int size();
}
实现接口:
//栈的特点:先进后出,后进先出
public class MyStack<E> implements MyVector<E> {
//以集合形式来保存栈
private List<E> list;
//栈顶指针
private int top;
public MyStack() {
list = new ArrayList<E>();
top = -1;
}
//如果top的值为-1表述栈为空
@Override
public boolean isEmpty() {
return top==-1;
}
//获取栈顶的元素
@Override
public synchronized E peek() {
return top == -1?null:list.get(top);
}
// 出栈的操作
@Override
public synchronized E pop() {
//不是为空栈
if(!isEmpty()){
E r = list.get(top);
list.remove(top);
top--;
return r;
}
return null;
}
@Override
public synchronized E push(E item) {
//判断item是否为空值
if(item == null){
return null;
}
list.add(item);
top++;
return item;
}
//栈的大小
@Override
public int size() {
return (top+1);
}
//查找某个元素的位置
@Override
public synchronized int search(Object o) {
if(!isEmpty()){
return -1;
}
if(o != null){
for(int i = 0 ; i < list.size();i++){
if(list.get(i).equals(o)){
return i;
}
}
}
return -1;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
使用单元测试测试:
public class TestAction {
private MyVector<String> stack;
@Before
public void before(){
System.out.println("测试开始");
stack = new MyStack<String>();
}
@Test
public void test() {
stack.push("hello");
stack.push("world");
System.out.println("栈的大小="+stack.size());
//判断栈是否为空
System.out.println("isEmpty="+stack.isEmpty());
//获取栈顶元素
String v = stack.peek();
System.out.println("peek value="+v);
//出栈
String first = stack.pop();
System.out.println("pop value="+first);
System.out.println("栈的大小="+stack.size());
//测试查找
System.out.println("位置:"+stack.search("hellofff"));
}
@After
public void after(){
System.out.println("测试结束");
stack = null;
}
结语:
以上皆是个人学习所用,不能肯定有很多的不足之处,望指点。如果需要交流可以关注我的公众号一起交流学习