Java--栈的数组实现
栈的Java代码:
package 栈的数组实现; public class MyStack { private long[] arr; private int top; public MyStack() { arr = new long[10]; top = -1; } public MyStack(int size) { arr = new long[size]; top = -1; } public void push(long value) { arr[++top] = value; } public long pop() { return arr[top--]; } public long peak() { return arr[top]; } public boolean isEmpty() { return (top == -1); } public boolean isFull() { return (top == arr.length - 1); } }
测试栈的特性:
package 栈的数组实现; public class MyStackDemo { public static void main(String[] args) { MyStack myStack = new MyStack(6); myStack.push(32132); myStack.push(876); myStack.push(22); myStack.push(86); myStack.push(332); myStack.push(87); System.out.println(myStack.isFull()); // true while (!myStack.isEmpty()) { System.out.print(myStack.pop());// 87, 332, 86, 22, 876, 32132 if (!myStack.isEmpty()) { System.out.print(", "); } } System.out.println(); System.out.println(myStack.isFull()); // false } }

浙公网安备 33010602011771号