本文目录一览:
java如何自定义栈?
public class Stack {
int[] data;
int maxSize;
int top;
public Stack(int maxSize) {
this.maxSize = maxSize;
data = new int[maxSize];
top = -1;
}
// 入栈
public boolean push(int data) {
// 入栈先判断栈中是否已满
if (top + 1 == maxSize) {
System.out.println("栈已满");
return false;
}
this.data[++top] = data;
return true;
}
// 出栈
public int pop() throws Exception {
// 出栈先判断栈是否已空
if (top == -1) {
throw new Exception("栈已空");
}
return this.data[top--];
}
public static void main(String[] args) throws Exception {
Stack stack = new Stack(1000);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
while (stack.top >= 0) {
System.out.println(stack.pop());
}
}
}
用java编写出来:用数组实现一个栈
public class Stack {
private Object[] stack;
private int size;
public Stack() {
this(10);
}
public Stack(int len) {
stack = new Object[len];
}
public int size() {
return size;
}
public int capacity() {
return stack.length;
}
public void ensureCapacity() {
if (size() == capacity()) {
Object[] newStack = new Object[size() * 3 / 2 + 1];
System.arraycopy(stack, 0, newStack, 0, size());
stack = newStack;
}
}
public void push(Object o) {
size++;
ensureCapacity();
stack[size - 1] = o;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new ArrayIndexOutOfBoundsException("不能为空");
}
Object o = stack[--size];
stack[size] = null;
return o;
}
public static void main(String[] args) {
Stack stack = new Stack(3);
String[] data = new String[]{"a", "b", "c"};
for (int i = 0; i < data.length; i++) {
stack.push(data[i]);
System.out.println(data[i] + "");
}
System.out.println("***********");
while (!stack.isEmpty()) {
System.out.println(stack.pop() + "");
}
}
}
你自己对比一下,我是在你的里面修改的。
java用链表实现栈
public Linked(Object element) {
this.element = element;
nextNode = null;
}
是啥意思,给值还return??把这函数删了