zoukankan      html  css  js  c++  java
  • 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;
    }

    }

  • 相关阅读:
    css 之优先策略
    SpringCloud WebUploader 分块上传
    SpringBoot WebUploader 分块上传
    java WebUploader 分块上传
    php WebUploader 分块上传
    jsp WebUploader 分块上传
    csharp WebUploader 分块上传
    c# WebUploader 分块上传
    .net WebUploader 分块上传
    c#.net WebUploader 分块上传
  • 原文地址:https://www.cnblogs.com/eryun/p/10398506.html
Copyright © 2011-2022 走看看