1、代码模拟
package org.gzw.ch03;
public class MyStack {
//底层实现一个数组
private long[] arr;
private int top;
/*无参构造*/
public MyStack() {
arr = new long[10];
top = -1;
}
/*有参构造*/
public MyStack(int maxsize){
arr = new long[maxsize];
top = -1;
}
/*添加数据*/
public void push(long value){
arr[++top] = value;
}
/*移除数据*/
public long pop(){
return arr[top--];
}
/*查看数据*/
public long peek(){
return arr[top];
}
/*判断是否为空*/
public boolean isEmpty(){
return top == -1;
}
/*判断是否满了*/
public boolean isFull(){
return top == arr.length-1;
}
}
2、测试
package org.gzw.ch03;
public class TestMyStack {
public static void main(String[] args) {
MyStack myStack = new MyStack(5);
myStack.push(99);
myStack.push(3);
myStack.push(-23);
myStack.push(1);
myStack.push(76);
//
System.out.println(myStack.isEmpty());
System.out.println(myStack.isFull());
System.out.print(myStack.peek() + ", ");
System.out.println(myStack.peek());
while(!myStack.isEmpty()){
System.out.print(myStack.pop() + ", ");
}
System.out.println();
System.out.println(myStack.isEmpty());
System.out.println(myStack.isFull());
}
}
3、运行结果
false
true
76, 76
76, 1, -23, 3, 99,
true
false