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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值