第三章、稀疏矩阵和队列

稀疏数组和二维数组的转化

  • 二维数组转化成稀疏数组思路
    • 创建一个二维数组chessArr[11][11],放入一些非零元素,并打印输出
    • 遍历二维数组,统计非零元素的个数num
    • 创建稀疏数组sparseArr[num + 1][3]
    • 遍历二维数组,把非零元素放到稀疏数组中,并打印输出
  • 稀疏数组转化成二维数组思路
    • 创建二维数组chessArr[sparseArr[0][0]][sparseArr[0][1]]
    • 遍历稀疏数组,把元素放到二维数组里,并打印输出
public class SparseArray {
    public static void main(String[] args) {
        //1.创建二维数组
        int chessArr[][] = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        chessArr[3][4] = 10;

        //2.输出二维数组
        System.out.println("原始的二维数组:");
        for (int[] ints : chessArr) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }

        System.out.println();

        //3.二维数组转稀疏数组
        //遍历二维数组统计非零元素个数
        int num = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0){
                    num++;
                }
            }
        }

        //创建稀疏数组
        int sparseArr[][] = new int[num + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = num;


        //把二维数组里的元素放到稀疏数组里
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0){
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr[i][j];
                }
            }
        }

        //查看稀疏矩阵的行数
        System.out.println("稀疏矩阵的行数:" + sparseArr.length);
        System.out.println();


        //4.输出稀疏数组
        System.out.println("转化的稀疏数组:");
        for (int[] ints : sparseArr) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }

        System.out.println();

        //5.稀疏数组转成二维数组
        //创建二维数组
        int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];

        //遍历稀疏数组,把元素加到二维数组里
        for (int i = 1; i < sparseArr.length; i++) {
            chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }

        //6.输出二维数组
        System.out.println("恢复后的二维数组:");
        for (int[] ints : chessArr2) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}

把稀疏数组打印到文件里并恢复

public class PrintSparseArray {
    public static void main(String[] args) throws Exception {
        //1.创建二维数组
        int chessArr[][] = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;
        chessArr[3][4] = 10;


        //3.二维数组转稀疏数组
        //遍历二维数组统计非零元素个数
        int num = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0) {
                    num++;
                }
            }
        }

        //创建稀疏数组
        int sparseArr[][] = new int[num + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = num;


        //把二维数组里的元素放到稀疏数组里
        int count = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j < 11; j++) {
                if (chessArr[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr[i][j];
                }
            }
        }

        //把稀疏数组打印到文件里
        //getBytes()方法:将一个字符串转化成字符数组
        FileOutputStream f = new FileOutputStream("DataStructures\\src\\chess.txt");
        for (int i = 0; i < sparseArr.length; i++) {
            f.write((sparseArr[i][0] + "\t" + sparseArr[i][1] + "\t" + sparseArr[i][2]).getBytes());
            if (i != sparseArr.length - 1){
                f.write("\n".getBytes());
            }
        }

        //把文件中的稀疏矩阵读进来并恢复成二维数组
        //split函数:把字符串根据括号里的内容分割成字符串数组
        //Inter.parseInt()函数:把字符串解析成十进制的整数
        BufferedReader br = new BufferedReader(new FileReader("DataStructures\\src\\chess.txt"));
        String line = "";
        int lineNum = 0;
        int chessArr2[][] = null;
        while((line = br.readLine()) != null){
            lineNum++;
            if (lineNum == 1){
                String[] array = line.split("\t");
                chessArr2 = new int[Integer.parseInt(array[0])][Integer.parseInt(array[1])];
            }else{
                String[] array = line.split("\t");
                chessArr2[Integer.parseInt(array[0])][Integer.parseInt(array[1])] =
                      Integer.parseInt(array[2]);
            }
        }

        //输出二维数组
        for (int[] ints : chessArr2) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }

    }
}

数组模拟顺序队列

public class ArrayQueue {
    private int maxSize; //数组的最大长度
    private int front; //指向队首元素的前一个位置
    private int rear; //指向队尾元素
    private int[] array; // 存放队列中的数据

    public ArrayQueue(int arraySize) {
        maxSize = arraySize;
        array = new int[maxSize];
//            int front = -1;  //重复定义了
//            int rear = -1;
        front = -1;
        rear = -1;
    }

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

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

    //入队
    public void EnQueue(int n){
        if (isFull()){
//                throw new RuntimeException("队列已满,入队失败"); //void类型不用报异常,给个提示信息就行
            System.out.println("队列已满,入队失败");
            return;
        }

        array[++rear] = n;
    }

    //出队
    public int DeQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,出队失败");
        }

//            int n = array[++front];
//            return n;
        return array[++front];
    }

    //显示队列中所有元素
    public void showQueue(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }

//            for (int i = 0; i < maxSize - 1; i++) {
//                System.out.println("array[i] = " + array[i]);
//            }
        int j = front + 1;
        for (int i = 0; i < (rear - front); i++) {
            System.out.println("array[" + i + "] = " + array[j]);
            j++;
        }
    }

    //显示队头元素,注意这里不是取出数据,不能使用++front
//        public void headQueue(){
//            if (isEmpty()){
//                throw new RuntimeException("队列为空");
//            }
//
//            System.out.println("队头元素为:" + array[front + 1]);
//        }
    public int headQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }

        return array[front + 1];
    }


}
public class test {
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        Scanner sc = new Scanner(System.in);
        boolean loop = true;
        char key;

        while (loop){
            System.out.println("'E'EnQueue:入队");
            System.out.println("'D'EeQueue:出队");
            System.out.println("'h'headQueue:查看头部元素");
            System.out.println("'s'showQueue:查看所有元素");
            System.out.println("'e'exit:退出");
            key = sc.next().charAt(0);

            switch (key){
                case 'E':
                    System.out.println("请输入一个数:");
                    int value = sc.nextInt();
                    queue.EnQueue(value);
                    break;
                case 'D':
                    try {
                        int n = queue.DeQueue();
                        System.out.println("取出的元素为:" + n);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 'h':
                    try {
                        int n = queue.headQueue();
                        System.out.println("头部元素为:" + n);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 's':
                    queue.showQueue();
                    break;
                case 'e':
                    loop = false;
                    break;
                default:
                    break;
            }
        }
    }
}

数组模拟循环队列

  • front初始值为0,指向队首元素
  • rear初始值为0,指向队尾元素的后一个位置
  • rear = front时队列为空
  • (rear + 1) % maxSize = front时队列满
  • 队列中的元素个数:(rear + maxSize - front)% maxSize
public class CircleQueue {
    private int maxSize; //数组的最大长度
    private int front; //指向队首元素的前一个位置
    private int rear; //指向队尾元素
    private int[] array; // 存放队列中的数据

    public CircleQueue(int arraySize) {
        maxSize = arraySize;
        array = new int[maxSize];
        front = 0;
        rear = 0;
    }

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

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

    //入队
    public void EnQueue(int n){
        if (isFull()){
            System.out.println("队列已满,入队失败");
            return;
        }

        array[rear] = n;
        rear = (rear + 1) % maxSize;
    }

    //出队
    public int DeQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空,出队失败");
        }

        int n = array[front];
        front = (front + 1) % maxSize;
        return n;
    }

    //显示队列中所有元素
    public void showQueue(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }

        for (int i = front; i < front + size(); i++) {
            System.out.println("array[" + i % maxSize + "] = " + array[i % maxSize]);
        }
    }

    //求数列中元素个数
    public int size(){
        return (rear + maxSize - front) % maxSize;
    }

    //显示队头元素,注意这里不是取出数据,不能使用++front
    public int headQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }

        return array[front];
    }
}
public class test {
    public static void main(String[] args) {
        CircleQueue queue = new CircleQueue(4);
        Scanner sc = new Scanner(System.in);
        boolean loop = true;
        char key;

        while (loop){
            System.out.println("'E'EnQueue:入队");
            System.out.println("'D'EeQueue:出队");
            System.out.println("'h'headQueue:查看头部元素");
            System.out.println("'s'showQueue:查看所有元素");
            System.out.println("'e'exit:退出");
            key = sc.next().charAt(0);

            switch (key){
                case 'E':
                    System.out.println("请输入一个数:");
                    int value = sc.nextInt();
                    queue.EnQueue(value);
                    break;
                case 'D':
                    try {
                        int n = queue.DeQueue();
                        System.out.println("取出的元素为:" + n);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 'h':
                    try {
                        int n = queue.headQueue();
                        System.out.println("头部元素为:" + n);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    break;
                case 's':
                    queue.showQueue();
                    break;
                case 'e':
                    loop = false;
                    break;
                default:
                    break;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值