데이터 구조 - 큐 (Java 구현)

데이터 구조 - 큐 (Java 구현)

블로그 설명

인터넷에서 관련 문서의 정보는 개인의 학습 경험과 요약, 침해하는 경우, 연락처 나 삭제하시기 바랍니다 무엇을, 감사합니다 의미, 개인적인 결론을 정리!

간략한 소개

대기열은 특정 선형 형태이며, 단지 테이블 (전면)의 선단에서 삭제할 수 있다는 점에서 특별하다 삽입 후단하면서 조작함으로써 큐로 테이블 (REAR) 및 스택 선형 제한 테이블. 끝의 테일 엔드라고도 삭제 작업은 헤드의 삽입 동작이라고한다 .

큐, 당신은 정렬 된 목록, 배열이나 달성하기 위해 연결리스트를 사용하는 따를 수있다 FIFO의 원칙을

배열 큐

도표

그림 삽입 설명 여기

생각

(1) 앞의 실제 초기 -1 값과 최대 값 MAXSIZE

2 공기 열 조건 : 후방 = 전면

3 큐 전체 상태 : 실제 MAXSIZE = -1

코드 구현

package queue;

import com.sun.source.tree.BreakTree;

import java.util.Iterator;
import java.util.Scanner;

public class ArrayQueue {
    public static void main(String[] args) {
        //创建一个对象
        Array queue = new Array(3);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop){
            System.out.println("请输入字符操作");
            System.out.println("输入s:显示队列");
            System.out.println("输入a:添加数据");
            System.out.println("输入g:取出数据");
            System.out.println("输入h:查看队列头");
            System.out.println("输入e:退出程序");
            key = scanner.next().charAt(0); //接收一个字符
            switch (key){
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("请输入一个数");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("取出的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");
    }
}

//使用数组模拟队列
class Array{
    private int maxSize; //表示最大的容量
    private int front;  //对列头
    private int rear;   //队列尾
    private int[] arr;    //存放数据

    //创建队列的构造器
    public Array(int arrMaxSize){
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        front = -1;  //指向队列头
        rear = -1;   //指向队列尾
    }

    //判断队列是否满了
    public boolean isFull(){
        return rear == maxSize - 1;
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return rear == front;
    }

    //添加数据到队列
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列满了,不能加数据了");
            return;
        }
        rear++;  //rear后移
        arr[rear] = n;
    }

    //获取队列的数据
    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,不能取数据");
        }
        front++;  //front后移
        return arr[front];
    }

    //显示队列的所有数据
    public void showQueue(){
        //遍历
        if (isEmpty()){
            throw new RuntimeException("队列为空,不能取数据");
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.printf("arr[%d]=%d\n",i,arr[i]);
        }
    }

    //显示队列的头数据
    public int headQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,不能取数据");
        }
        return arr[front + 1];
    }
}

테스트

[해외 체인의 사진은, 소스 스테이션 보안 체인 메커니즘을 가질 수있다 실패 투기, (IMG가-VHiKUAIr-1584705260920) (/ 사용자 / tanglei / 라이브러리 / 응용 프로그램 지원 / typora 사용자-이미지 / 이미지 20200320195326718 직접 업로드 아래 그림을 저장하는 것이 좋습니다 .PNG)]

데이터를 추가 할 필요가 있습니다 요를 액세스 할 수 있습니다.

결함

배열은 한 번만 사용할 수 있습니다

어레이를 이용하여 아날로그 환형 어레이

도표

그림 삽입 설명 여기

생각

1 폰트 초기 값은 0이고, 첫 번째 요소는 큐는

2, 실제의 초기 값은 0, 큐의 마지막 요소에 대한 요소 (의지 규칙으로 비워진 위치) 인

3, 전체 열의 조건 : (레알 +1) 개조 MAXSIZE = 전면

4 큐 비어 조건 : 실제 = 전면

5 유효 데이터 큐의 수 (실제 + MAXSIZE 앞) 개조 MAXSIZE

코드

package queue;

import java.util.Scanner;

public class CricleArrayQueue {
    public static void main(String[] args) {
        //创建一个对象
        CricleArray queue = new CricleArray(4);  //有效数据为3
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop){
            System.out.println("请输入字符操作");
            System.out.println("输入s:显示队列");
            System.out.println("输入a:添加数据");
            System.out.println("输入g:取出数据");
            System.out.println("输入h:查看队列头");
            System.out.println("输入e:退出程序");
            key = scanner.next().charAt(0); //接收一个字符
            switch (key){
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("请输入一个数");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = queue.getQueue();
                        System.out.printf("取出的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = queue.headQueue();
                        System.out.printf("队列头的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("程序退出");
    }
}

//使用数组模拟环形队列
class CricleArray{
    private int maxSize; //表示最大的容量
    private int front;  //对列头
    private int rear;   //队列尾
    private int[] arr;    //存放数据

    //创建队列的构造器
    public CricleArray(int arrMaxSize){
        maxSize = arrMaxSize;
        arr = new int[maxSize];
    }

    //判断队列是否满了
    public boolean isFull(){
        return (rear + 1) % maxSize == front;
    }

    //判断队列是否为空
    public boolean isEmpty(){
        return rear == front;
    }

    //添加数据到队列
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列满了,不能加数据了");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1) % maxSize;  //rear后移
    }

    //获取队列的数据
    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,不能取数据");
        }
        int value = arr[front];
        front = (front + 1) % maxSize;//front后移
        return value;
    }

    //显示队列的所有数据
    public void showQueue(){
        //遍历
        if (isEmpty()){
            System.out.println("");
            throw new RuntimeException("");
        }
        for (int i = front; i < front+size(); i++) {
            System.out.printf("arr[%d]=%d\n",i % maxSize,arr[i % maxSize]);  //格式化输出
        }
    }

    //求出当前队列有效数据的个数
    public int size(){
        return (rear + maxSize -front) % maxSize;
    }

    //显示队列的头数据
    public int headQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,不能取数据");
        }
        return arr[front];
    }
}


테스트

그림 삽입 설명 여기

감사

바이두 백과 사전

범용 네트워크

그리고 열심히 소유

게시 된 171 개 원래 기사 · 원 찬양 (414) ·은 20000 +를 볼

추천

출처blog.csdn.net/qq_45163122/article/details/104997271