您的位置:

java实现栈,java实现栈的类

本文目录一览:

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 top = 0; //初始化栈顶

//这个也不需要;

//写一个栈出来,最好是可以动态的,可以自己改变大小的,即数组的长度;

//private int size = 0; // 初始化大小

//元素个数;

private int size;

//默认长度为10;

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 void push(Object object) {

if (isFull()) {

System.out.println("栈满! 入栈失败");

}

stack[top++] = object;

}

*/

//判空;

public boolean isEmpty(){

return size == 0;

}

//出栈;

public Object pop(){

//首先要判空;

if(isEmpty()){

throw new ArrayIndexOutOfBoundsException("不能为空");

}

Object o = stack[--size];

stack[size] = null;

return o;

}

/*

// 出栈

public Object pop() {

Object object = stack[--top];

stack[top] = null;

return object;

}

*/

/*

// 计算栈当前大小

public int size() {

return top;

}

// 判断是否是空栈

public boolean isEmpey() {

return top == 0;

}

// 判断是否栈满

public boolean isFull() {

return top = size;

}

public Stack(int size) {

this.size = size;

}

*/

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 Object setEle(Object element)

{

Object oldElement = this.element;

this.element = element;

return oldElement;

}

是啥意思,给值还return??把这函数删了

public Linked()

{

nextNode = null;

element = null;

}

改成

public Linked(Object element)

{

this.element = element;

nextNode = null;

}