异常为空栈异常:
public class EmptyStackException extends RuntimeException {
public EmptyStackException(){
}
public EmptyStackException(String msg){
super(msg);
}
}
循环队列:
class MyCircularQueue {
public int[] elem;
public int front;//队头下标
public int rear;//队尾下标
public MyCircularQueue(int k) {
this.elem=new int[k+1];
}
//入队
public boolean enQueue(int value) {
if(isFull()){
return false;
}
this.elem[rear]=value;
rear=(rear+1) % elem.length;
return true;
}
//出队
public boolean deQueue() {
if (isEmpty()){
return false;
}
front=(front+1)%elem.length;
return true;
}
//获取队头元素
public int Front() {
if (isEmpty()){
return -1;
}
return elem[front];
}
//获取队尾元素
public int Rear() {
if (isEmpty()){
return -1;
}
int index=(rear==0)?elem.length-1:rear-1;
return elem[index];
}
public boolean isEmpty() {
return rear==front;
}
public boolean isFull() {
return (rear+1) % elem.length==front;
}
}
普通队列:
import java.util.Queue;
//链式队列
public class MyQueue {
static class Node{
public int val;
public Node next;
public Node(int val){
this.val=val;
}
public Node head;//队列的头
public Node tail;//队列的尾
/*
入队操作
*/
public void offer(int val){
Node node=new Node(val);
if(head==null){
head=node;
tail=node;
}else {
tail.next=node;
tail=tail.next;
}
}
/*
出队操作
*/
public int poll(){
if(head==null){
return -1;
}
int oldVal=head.val;
if (head.next==null){
head=tail=null;
}else {
head=head.next;
}
return oldVal;
}
/*
查看当前队头元素
*/
public int peek(){
if(head==null){
return -1;
}
return head.val;
}
}
}
栈:
import com.sun.scenario.effect.impl.prism.PrReflectionPeer;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Stack;
public class MyStack {
public int[] elem;
public int usedSize;
//当前栈当中存储的有效数据个数
public static final int size=10;
public MyStack(){
elem=new int[size];
}
/*
判断当前栈是否是满的
*/
public boolean isFull(){
if(usedSize==elem.length){
return true;
}
return false;
}
/*
判断栈是否为空
*/
public boolean isEmpty(){
return usedSize==0;
}
/**
* 压栈
*/
public void push(int val){
//1.判断栈是否是满的
if (isFull()){
elem= Arrays.copyOf(elem,2*elem.length);
}
//存放到当前的下标,同时usedSize需要自增
elem[usedSize]=val;
usedSize++;
}
/*
删除栈顶元素
*/
public int pop(){
if(isEmpty()){
throw new EmptyStackException("栈为空");
}
int oldVal=elem[usedSize-1];
usedSize--;
return oldVal;
}
/*
获取栈顶元素但是不删除
*/
public int peek(){
if (isEmpty()){
throw new EmptyStackException("栈为空了");
}
return elem[usedSize-1];
}
}