0
点赞
收藏
分享

微信扫一扫

设计一个自己的循环队列和栈

一、设计循环队列(力扣622题: 设计循环队列)

public class MyCircularQueue {

    private int[] elem;
    private int front;
    private int rear;

    public MyCircularQueue(int k) {
        this.elem = new int[k + 1];
    }

    //入队(队尾入队)
    public boolean enQueue(int value) {
        if(isFull()) {
            return false;
        }
        this.elem[this.rear] = value;
        this.rear = (this.rear + 1) % this.elem.length;//防止从最后一个位置走到第一个位置
        return true;
    }

    //出队(对头出队)
    public boolean deQueue() {
        if(isEmpty()) {
            return false;
        }
        this.front = (this.front + 1) % this.elem.length;
        return true;
    }

    //得到队头元素
    public int Front() {
        if(isEmpty()) {
            return -1;
        }
        return this.elem[this.front];
    }

    //得到队尾元素
    public int Rear() {
        if(isEmpty()) {
            return -1;
        }
        int index = -1;
        if(this.rear == 0) {
            index = elem.length - 1;
        }else {
            index = this.rear - 1;
        }
        return this.elem[index];
    }

    public boolean isEmpty() {
        return this.front == this.rear;
    }

    public boolean isFull() {
        return this.front == (this.rear + 1) % this.elem.length;
    }
}
public class TestDemo {
     public static void main(String[] args) {
         MyCircularQueue myCircularQueue = new MyCircularQueue(5);
         myCircularQueue.enQueue(4);
         myCircularQueue.enQueue(5);
         myCircularQueue.enQueue(4);
         myCircularQueue.deQueue();//删除队头元素
         System.out.println(myCircularQueue.Front());
         System.out.println(myCircularQueue.Rear());
     }
}

二、设计栈

public class MyStack {
    public int[] elem;
    public int usedSize;

    public MyStack() {
        this.elem = new int[5];
    }

    //压栈==入栈
    public void push(int val) {
        if(isFull()) {
            System.out.println("栈满了!");
            return;
        }
        this.elem[this.usedSize++] = val;
    }

    public boolean isFull() {
        return this.usedSize == this.elem.length;
    }

    //弹出栈顶元素
    public int pop() throws RuntimeException {
        if(empty()) {
            throw new RuntimeException("栈为空!");
        }
        int val = this.elem[this.usedSize - 1];
        this.usedSize--;
        return val;
    }

    public boolean empty() {
        return this.usedSize == 0;
    }
    //只是获取栈顶元素 但是不删除
    public int peek() {
        if(empty()) {
            throw new RuntimeException("栈为空!");
        }
        return this.elem[this.usedSize - 1];
    }
}
public class TestDemo {
    public static void main1(String[] args) {
        MyStack myStack = new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        System.out.println(myStack.pop());
        System.out.println(myStack.peek());
        System.out.println(myStack.empty());
    }
}
举报

相关推荐

0 条评论