java实现队列和栈

  队列:队列其实就是我们生活中的排队现象,先进入的先出,后进入的后出,代码实现如下:

public class Queue<E> {

private int front;//队头一端,只允许删除

private int rear;//队尾一端,只允许插入操作

private int max_size =16;

private Object[] data;

public Queue() {
this(10);
}
public Queue(int size){
if(size<0){
throw new IllegalArgumentException("队列初始化失败,原因是:"+size);
}
this.max_size = size;
front = rear = 0;
data = new Object[max_size];
}
//判断是否为空
public boolean isEmpty(){
return rear==front?true:false;
}
//入队
public boolean add(E e){
if(rear==max_size){
throw new RuntimeException("队列满了");
}else{
data[rear++] = e;
return true;
}
}
//返回队首元素,不删除元素
public E peek(){
if(isEmpty()){
return null;
}
return (E) data[front];
}
//出队
public E poll(){
if(isEmpty()){
throw new RuntimeException("队列为空");
}
else{
E e = (E) data[front];
data[front++] = null;
return e;
}
}
//长度
public int length(){
return rear-front;
}
}

public class Queue<T> {
private Object[] data; //存储数据
private int head; //头
private int tail; //尾

public Queue(){
data = new Object[100];//为了说明原理随意指定
head =1;
tail =1;
}
public void put(T t){
data[tail] =t;
tail++;
}
public T get(){
T t =(T) data[head];
head ++;
return t;
}
}

栈:

package test;

public class stack {

private int maxSize;// 栈的大小
private int top;
private char[] arr;

public stack(int size) {
maxSize = size;
top = -1;
arr = new char[maxSize];
}

public void push(char value) { // 压入数据

arr[++top] = value;
}

public char pop() { // 弹出数据

return arr[top--];
}

public char peek() { // 访问栈顶元素

return arr[top];
}

public boolean isFull() { // 栈是否满了

return maxSize - 1 == top;
}

public boolean isEmpty() { // 栈是否为空

return top == -1;
}

}

原文地址:https://www.cnblogs.com/eryun/p/10398506.html