栈和队列的实现

数组实现栈

/**
 *数组实现栈,需要"数组,末端索引,初始容量"
 */
public class ArrayStack {

//数组初始容量,由于是数组实现,需要考虑扩容问题
    private int DEFAULT_CAPCITY = 10;
    private int[] array;
    private int topOfStack = -1;

//    使用默认初始容量
    public ArrayStack(){
        array = new int[DEFAULT_CAPCITY];
    }

//    使用指定初始容量
    public ArrayStack(int capacity){
        array = new int[capacity];
    }

    public void makeEmpty(){
        topOfStack = -1;
    }

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

    public void push(int x){
//        此时需要扩容
        if(topOfStack + 1 == array.length){
            array = Arrays.copyOf(array,DEFAULT_CAPCITY*2);
        }
        array[++topOfStack] = x;
    }

    public void pop(){
        if(isEmpty()){
            return;
        }
        topOfStack--;
    }
}

链表实现栈

/**
 * 链表实现栈,链表的第一项表示栈顶元素
 */
public class ListNodeStack {

    class ListNode{
        public int element;
        public ListNode next;
        public ListNode(int theElement, ListNode theNext){
            this.element = theElement;
            this.next = theNext;
        }
    }

    private ListNode topOfStack = null;

    public void makeEmpty(){
        topOfStack = null;
    }

    public boolean isEmpty(){
        return topOfStack == null;
    }

    public void push(int x){
        topOfStack = new ListNode(x,topOfStack);
    }

    public void pop(){
        if(isEmpty()){
            return;
        }
        topOfStack = topOfStack.next;
    }

}

链表实现队列

/**
 * 链表实现队列,需要"队首元素和队尾元素的引用"
 */
public class ListNodeQueue {

    class ListNode{
        private ListNode next;
        private int element;
        public ListNode(int theElement, ListNode theNext){
            this.element = theElement;
            this.next = theNext;
        }
    }

    private ListNode front = null;
    private ListNode back = null;

    public void makeEmpty(){
        front = null;
        back = null;
    }

    public boolean isEmpty(){
        return front == null;
    }

    public void enqueue(int x){
        if(isEmpty()){
            front = new ListNode(x,null);
            back = front;
        } else {
            back.next = new ListNode(x,null);
            back = back.next;
        }
    }

    public void dequeue(){
        if(isEmpty()){
            return;
        } else {
            front = front.next;
        }
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值