Java学习笔记Day16:栈和队列

栈(先进后出)

栈的方法:

  • E push(E item)压栈
  • E pop() 出栈
  • E peek() 查看栈顶元素
  • boolean empty() 判断栈是否为空

顺序表实现栈

public class MyStack {
	private int[] array = new int[100];
	array[size++] = v;
	public void push(int v) {
		array[size++] = v;
	}
	public int pop() {
		return array[--size];
	}
	public int peek() {
		return array[size - 1];
	}
	public boolean isEmpty() {
		return size == 0;
	}
	public int size() {
		return size;
	}
}

队列(先进后出)

队列的方法

错误处理 抛出异常 返回特殊值
入队列 add(e) offer(e)
出队列 remove() poll()
队首元素 element() peek()

循环队列

循环队列的实现

class MyCircularQueue {
    int[] a;
    int front;
    int rear;
    int size;
    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        a=new int[k+1];
       front=rear=0;
       size=k+1;
    }
    
    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if(isFull()){
            return false;
        }
        a[rear]=value;
        rear=(rear+1)%size;
        return true;
    }
    
    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if(isEmpty()){
            return false;
        }
        front=(front+1)%size;
        return true;
    }
    
    /** Get the front item from the queue. */
    public int Front() {
        if(isEmpty()){
            return -1;
        }
       return a[front]; 
    }
    
    /** Get the last item from the queue. */
    public int Rear() {
        if(isEmpty()){
            return -1;
        }
        return a[(rear-1+size)%size];
    }
    
    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        if(front==rear){
            return true;
        }
        return false;
    }
    
    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        if((rear+1)%size==front){
            return true;
        }
        return false;
    }
}


发布了67 篇原创文章 · 获赞 12 · 访问量 1476

猜你喜欢

转载自blog.csdn.net/qq_42174669/article/details/103981077