java的队列和栈_java实现队列和栈

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

public class Queue {

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 {

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;

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值