• D1-数据结构基础、稀疏数组和队列[Java数据结构和算法]


    1. 数据结构

      1.1 线性结构

      (1)最常用的数据结构,特点是数据元素之间存在一对一的线性关系

      (2)有两种不同的存储结构,即顺序存储结构和链式存储结构

        -顺序存储的线性表称为顺序表,顺序表中的存储元素是连续的

        -链式存储的线性表称为链表,链表中的存储元素不一定是连续的,元素节点中存放数据元素以及相邻元素的地址信息

      (3)常见的有:数组、队列、链表和栈

      1.2 非线性结构

      包括:二维数组,多维数组,广义表,树结构,图结构 

    2.稀疏数组和队列

      2.1 稀疏sparsearray数组

      (1)实际需求:编写五子棋程序,有存盘退出和续上盘的功能

        

        -问题分析:因为该二维数组的很多值是默认值0,因此记录了很多没有意义的数据--->稀疏数组

      (2)基本介绍

      -当一个数组中的大部分元素为0,或者为同一个值的数组时,可以使用稀疏数组来保存该数组。

      -稀疏数组的处理方法:

        --记录数组一共有几行几列,有多少个不同的值

        --把具有不同值的行列及值记录在一个小规模的数组中,从而缩小程序的规模

      

      2.2 应用实例分析

      (1)二维数组转稀疏数组的思路

        -遍历原始二维数组,得到有效数据的个数sum

        -根据sum创建稀疏数组sparseArr int[sum+1][3]

        -将二维数组的有效数据存入到稀疏数组

      (2)稀疏数组转原始的二维数组的思路

        -读取稀疏数组第一行,根据第一行数据创建原始二维数组,如chessArr=int[11][11]

        -读取稀疏数组后几行的数组,赋值给原始的二维数组

      (3)代码实现

    public static void main(String[] args)throws Exception {
            // TODO Auto-generated method stub
            //创建一个原始的二维数组11*11
            //0:表示没有棋子,1表示黑子,2表示蓝子
            int chessArr1[][]=new int[11][11];
            chessArr1[1][2]=1;
            chessArr1[2][4]=2;
            //输出原始的二维数组
            System.out.println("原始的二维数组:");
            for(int[] row:chessArr1){
                for(int data:row)
                    {
                    System.out.printf("%d	",data);
                    }
                System.out.println();
            }
            
            //将二维数组转稀疏数组的思想
            //1.先遍历二维数组得到非0数据的个数
            int sum=0;
            for(int i=0;i<11;i++){
                for(int j=0;j<11;j++){
                    if(chessArr1[i][j]!=0){
                        sum++;
                    }
                }
            }
            System.out.println(sum);
            
            //2.创建对应的稀疏数组
            int sparseArr[][]=new int[sum+1][3];
            //给稀疏数组赋值
            sparseArr[0][0]=11;
            sparseArr[0][1]=11;
            sparseArr[0][2]=sum;
            
            //创建map.data文件
            File map1=new File("map.data");
            FileWriter fw=new FileWriter(map1);
            fw.write(11+"	");    
            fw.write(11+"	");
            fw.write(sum+"	");
            //遍历二维数组,存放到稀疏数组中
            int count=0;//count 用于记录是第几个非0书
            for(int i=0;i<11;i++){
                for(int j=0;j<11;j++){
                    if(chessArr1[i][j]!=0){
                        count++;
                        sparseArr[count][0]=i;
                        sparseArr[count][1]=j;
                        sparseArr[count][2]=chessArr1[i][j];
                        //将稀疏数组存入map.data
                        fw.write(i+"	");    
                        fw.write(j+"	");
                        fw.write(chessArr1[i][j]+"	");
                    }    
                }fw.write("
    ");
            }
            fw.close();
            
            //文件读取
            BufferedReader br=new BufferedReader(new FileReader(map1));
            String line;
            int row1=0;
            //逐行读取,将每个数组放入数组中去
            while((line=br.readLine())!=null){
                String[] temp=line.split("	");
                for(int j=0;j<temp.length-1;j++){
                    sparseArr[row1][j]=Integer.parseInt(temp[j]);    
                }
                row1++;
            }
            br.close();
            //输出稀疏数组的形式
            System.out.println();
            System.out.println("输出稀疏数组的形式为");
            for(int i=0;i<sparseArr.length;i++){
                System.out.printf("%d	%d	%d	
    ",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
            }
            
            
            
            
            //将稀疏数组恢复成 原始二维数组
            //1.先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组
            int chessArr2[][]=new int[sparseArr[0][0]][sparseArr[0][1]];
            
            
            //2.在读取稀疏数组后几行的数据,并赋值给原始的二维数组即可
            for(int i=1;i<=sparseArr[0][2];i++){
                    chessArr2[sparseArr[i][0]][sparseArr[i][1]]=sparseArr[i][2];
            }
            //输出恢复后的二维数组
            System.out.println();
            System.out.println("恢复后的二维数组");
            for(int[] row:chessArr2){
                for(int data:row)
                    {
                    System.out.printf("%d	",data);
                    }
                System.out.println();
            }
        }

      2.3 队列

      (1)队列介绍

        -队列是一个有序列表,可以用数组或是链表来实现

        -遵循先入先出的原则

        -示意图

                  

      (2)数组模拟队列

        -队列本身是有序列表,若使用数据的结构来存储队列的数据,则队列数组的声明如上图,其中maxSize为该队列最大容量

        -因为队列的输出输入是分别从前后端处理,因此需要两个变量front及rear分别记录前后端的下标,front会随着数据输出改变,rear会随着数据输入改变

        -数据存入队列addQueue

          --将尾指针往后移:rear+1,当front==rear[空]

          --若尾指针rear小于队列的最大下标maxSize-1,则将数据存入rear所指的数组元素中,否则无法存入数据。rear==maxSize-1[队列满]

    public class ArrayQueueDemo {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            //创建一个队列
            ArrayQueue arrayQueue=new ArrayQueue(3);
            char key=' ';//接收用户输入
            Scanner sc=new Scanner(System.in);
            boolean loop=true;
            //输出一个菜单
            while(loop){
                System.out.println("s(show):显示队列");
                System.out.println("e(exit):退出程序");
                System.out.println("a(add):添加数据到队列");
                System.out.println("g(get):从队列取出数据");
                System.out.println("h(head):查看队列头的数据");
                key=sc.next().charAt(0);//接受一个字符
                switch(key){
                case's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数:");
                    int value=sc.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try{
                        int res=arrayQueue.getQueue();
                        System.out.printf("取出的数组是%d
    ",res);
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try{
                        int res=arrayQueue.headQueue();
                        System.out.printf("队列头的数据是%d
    ",res);
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    sc.close();
                    loop=false;
                    break;
                default:
                    break;
                }
                
            }
            System.out.println("程序退出");
        }
    
    }
    
    //使用数组模拟队列-编写一个ArrayQueue类
    class ArrayQueue{
        private int maxSize;//表示数组的最大容量
        private int front;//队列头
        private int rear;//队列尾
        private int[] arr;//该数组用于存放数组
        
        //创建队列构造器
        public ArrayQueue(int arrMaxSize){
            maxSize=arrMaxSize;
            arr=new int[maxSize];
            front=-1;//指向队列头部,分析出front是指向队列头的前一个位置
            rear=-1;//指向队列尾,指向队列尾的数据(即就是队列的最后一个数据)
        }
        
        //判断队列是否满
        public boolean isFull(){
            return rear==maxSize-1;
        }
        
        //判断队列是否为空
        public boolean isEmpty(){
            return front==rear;
        }
        
        //添加数据到队列
        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()){
                System.out.println("队列空的,没有数据");
                return;
            }
            for(int i=0;i<arr.length;i++){
                System.out.printf("arr[%d]=%d
    ",i,arr[i]);
            }
        }
        
        //显示队列的头数据,注意不是取出数据
        public int headQueue(){
            //判断
            if(isEmpty()){
                throw new RuntimeException("队列空,不能取数据");
            }
            return arr[front+1];
            
        }
    }

        --问题:目前数组使用一次就不能使用,没有达到复用的效果

            将这个数组改成环形队列,取模:%

      -数组模拟环形队列

        --调整front变量的含义:front指向队列的第一个元素,arr[front]就是队列的第一元素

        --front的初始值=0

        --调整rear变量的含义:rear指向队列的最后一个元素的后一个位置,希望空出一个空间作为约定

        --rear的初始值=0

        --队列满,条件是(rear+1)%maxSize==front

        --队列空,条件是rear==front

        --队列中有效的数据个数为(rear+maxSize-front)%maxSize

        

    public class CircleArrayQueueDemo {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            // TODO Auto-generated method stub
            //创建一个队列
            CircleArray arrayQueue=new CircleArray(4);//说明设置4,其队列的有效数据最大是3
            char key=' ';//接收用户输入
            Scanner sc=new Scanner(System.in);
            boolean loop=true;
            //输出一个菜单
            while(loop){
                System.out.println("s(show):显示队列");
                System.out.println("e(exit):退出程序");
                System.out.println("a(add):添加数据到队列");
                System.out.println("g(get):从队列取出数据");
                System.out.println("h(head):查看队列头的数据");
                key=sc.next().charAt(0);//接受一个字符
                switch(key){
                case's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数:");
                    int value=sc.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try{
                        int res=arrayQueue.getQueue();
                        System.out.printf("取出的数组是%d
    ",res);
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try{
                        int res=arrayQueue.headQueue();
                        System.out.printf("队列头的数据是%d
    ",res);
                    }catch(Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    sc.close();
                    loop=false;
                    break;
                default:
                    break;
                }
                
            }
            System.out.println("程序退出");
        }
    }
        
        
    class CircleArray{    
        private int maxSize;//表示数组的最大容量
        //调整front变量的含义:front指向队列的第一个元素,arr[front]就是队列的第一元素,front的初始值=0
        private int front;//队列头
        //调整rear变量的含义:rear指向队列的最后一个元素的后一个位置,希望空出一个空间作为约定,rear的初始值=0
        private int rear;//队列尾
        private int[] arr;//该数组用于存放数组
        
        //创建队列构造器
        public CircleArray(int arrMaxSize){
            maxSize=arrMaxSize;
            arr=new int[maxSize];
        }
        
        //判断队列是否满
        public boolean isFull(){
            return (rear+1)%maxSize==front;
        }
        
        //判断队列是否为空
        public boolean isEmpty(){
            return front==rear;
        }
        
        //添加数据到队列
        public void addQueue(int n){
            if(isFull()){
                System.out.println("队列满,不能加入数据");
                return;
            }
            //直接将数据加入
            arr[rear]=n;
            //将rear后移,这里必须考虑取模
            rear=(rear+1)%maxSize;
        }
        
        //获取队列的数据,出队列
        public int getQueue(){
            if(isEmpty()){
                //通过抛出异常
                throw new RuntimeException("队列空,不能取数据");
            }
            //需要分析front是指向队列的第一个元素
            //1.先把front对应的值保留到一个临时变量
            //2.将front后移
            //3.将临时保存的变量返回
            int value=arr[front];
            front=(front+1)%maxSize;
            return value;
            
        }
        
        //显示队列的所有数据
        public void showQueue(){
            //遍历
            if(isEmpty()){
                System.out.println("队列空的,没有数据");
                return;
            }
            //从front开始遍历,遍历多少个元素
            //
            for(int i=front;i<front+size();i++){
                System.out.printf("arr[%d]=%d
    ",i%maxSize,arr[i%maxSize ]); 
            }
        }
        //求出当前队列有效的个数
        public int size(){
            return (rear+maxSize-front)%maxSize;
        }
        //显示队列的头数据,注意不是取出数据
        public int headQueue(){
            //判断
            if(isEmpty()){
                throw new RuntimeException("队列空,不能取数据");
            }
            return arr[front ];
            
        }
        
    }
  • 相关阅读:
    JS(五)
    typescript(02)
    typescript(01)
    opensuse15.1字符界面下配置网络
    docker 再次学习
    load dll get last error 14001 Error: The Side-by-Side configuration information for XXXX.DLL contains errors. sxstrace.exe (14001).
    DRF序列化与反序列化
    《流畅的python》:生成字典的几种方式
    《流畅的python》:bisect来管理已排序的序列
    《流畅的python》:由*初始化一个由列表组成的列表
  • 原文地址:https://www.cnblogs.com/ERFishing/p/10957437.html
Copyright © 2020-2023  润新知