数据结构与算法(2)—— 栈(java)

1 栈的实现

1.1 简单数组实现栈

package mystack;

public class ArrayStack {
    private int top; //当前栈顶元素的下标
    private int[] array;

    public ArrayStack() {
        array = new int[10];
        top = -1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == array.length - 1;
    }

    public void push(int data) {
        if (isFull()) System.out.println("Stack Overflow!!");
        else {
            array[++top] = data;
        }
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack is empty!!");
            return 0;
        } else {
            return array[top--];
        }
    }

    public void deleteStack() {
        top = -1;
    }

}

1.2 动态数组实现栈

package mystack;

public class DynArrayStack {
    private int top;
    private int capacity;
    private int[] array;

    public DynArrayStack(int capacity) {
        this.capacity = capacity;
        array = new int[capacity];
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public boolean isFull() {
        return top == array.length - 1;
    }

    public void push(int data) {
        if (isFull()) doubleStack();
        array[++top] = data;
    }

    private void doubleStack() {
        int newArray[] = new int[array.length * 2];
        System.arraycopy(array, 0, newArray, 0, array.length);
        array = newArray;
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack Overflow!!!");
            return -1;
        }
        else return array[top--];
    }

    public void deleteStack() {
        top = -1;
    }

}

1.3 链表实现栈

public class LLStack {
private LLNode headNode;
public LLStack(){
	this.headNode = new LLNode(null);

}

public void Push(int data){
	if(headNode==null) {
		headNode = new LLNode(data);
	}else if(headNode.getData() == null) {
		headNode.setData(data);
	}else{
		LLNode llNode = new LLNode(data);
		llNode.setNext(headNode);
		headNode = llNode;
	}
}

public int pop(){
	if(headNode == null) return -1;
	else{
		int data = headNode.getData();
		headNode = headNode.getNext();
		return data;
	}
}

public boolean isEmpty(){
	if(headNode == null) return true;
	else return fasle;
}

public void deleteStack(){
	headNode = null;
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值