数据结构与算法

数据结构与算法

数组
  1. 将二维数组转换为稀疏数组
public class SparseArray {
    public static void main(String[] args) throws Exception{
        int[][] chessArray = new int[11][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        chessArray[2][5] = 2;
        //输出原始二维数组
        System.out.println("原始的二维数组:");
        for (int [] row : chessArray){
            for (int data : row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
        //将二维数组转为稀疏数组
        //遍历二维数组,获取有多少个值
        System.out.println("*****************************");
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j <11; j++){
                if (chessArray[i][j] != 0){
                    sum++;
                }
            }
        }
        System.out.println("sum = "+sum);

        //创建稀疏数组
        int[][] sparseArray = new int[sum+1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        //遍历数组,将数组中非零值记录到稀疏数组中
        int account = 0;
        // 用于记录是第几个非零数据
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j <11; j++){
                if (chessArray[i][j] != 0){
                    account++;
                    sparseArray[account][0]=i;
                    sparseArray[account][1]=j;
                    sparseArray[account][2]=chessArray[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("***********************************");
        for (int[] ints : sparseArray) {
            System.out.printf("%d\t%d\t%d\t\n", ints[0], ints[1], ints[2]);

        }

        System.out.println();

        System.out.println("************************\n");
        //将稀疏数组转换为普通数组
        //1. 创建一个数组
        int[][] chessArray1 = new int[sparseArray[0][0]][sparseArray[0][1]];
        //2.将稀疏数组的值赋给数组
        for (int i =1; i <sum+1 ; i++){
            chessArray1[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        for (int [] row : chessArray1){
            for (int data : row) {
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
    }
}

2.二维数组转换为稀疏数组+将数据输出到文件

public class SparseArray01 {
    public static void main(String[] args) throws Exception{
        FileOutputStream fos = new FileOutputStream("D:\\rjkf\\study\\数据结构\\SparseArray01.txt");
        FileInputStream fis = new FileInputStream("D:\\rjkf\\study\\数据结构\\SparseArray01.txt");
        int[][] chessArray = new int[11][11];
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        chessArray[2][5] = 2;
        //输出原始二维数组
        System.out.println("原始的二维数组:");
        for (int [] row : chessArray){
            for (int data : row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
        //将二维数组转为稀疏数组
        //遍历二维数组,获取有多少个值
        System.out.println("*****************************");
        int sum = 0;
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j <11; j++){
                if (chessArray[i][j] != 0){
                    sum++;
                }
            }
        }
        System.out.println("sum = "+sum);

        //创建稀疏数组
        int[][] sparseArray = new int[sum+1][3];
        sparseArray[0][0] = 11;
        sparseArray[0][1] = 11;
        sparseArray[0][2] = sum;
        //遍历数组,将数组中非零值记录到稀疏数组中
        int account = 0;
        // 用于记录是第几个非零数据
        for (int i = 0; i < 11; i++) {
            for (int j = 0; j <11; j++){
                if (chessArray[i][j] != 0){
                    account++;
                    sparseArray[account][0]=i;
                    sparseArray[account][1]=j;
                    sparseArray[account][2]=chessArray[i][j];
                }
            }
        }
        //输出稀疏数组
        System.out.println("***********************************");
        for (int[] ints : sparseArray) {
            System.out.printf("%d\t%d\t%d\t\n", ints[0], ints[1], ints[2]);

        }
        //把稀疏数组输出到硬盘中
        fos.write(Arrays.deepToString(sparseArray).getBytes());

        System.out.println();
        System.out.println("************************\n");
        //将稀疏数组转换为普通数组
        //读取文件中的稀疏数组
        byte[] buf = new byte[1024];
        int data = 0;
        while ((data=fis.read(buf))!=-1){
            System.out.println(new String(buf,0,data));
        }
        System.out.println("&*****************");
        //1. 创建一个数组
        fis.close();
        fos.close();
    }
}
  • 思考:将文件中的数据应用到程序中转换到原始数组!

3.数组模拟队列

package queue;

import java.util.Scanner;

/**
 1. 数组模拟队列:数组只能使用一次,不能重复使用
 2. 优化:适用环形队列   取模:%
 3. 队列:先入先出的特点
 4. @author りChic丶安漾
 */
public class ArrayQueueDemo {
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        //接收用户输入
        char key = ' ';
        Scanner scanner = 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 = scanner.next().charAt(0);
            switch (key){
                case 's':
                    queue.show();
                    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 ArrayQueue {
    //队列最大值
    private int maxSize;
    //队列头
    private int front;
    //队列尾
    private int rear;
    private int[] arr;
    //创建队列的构造器
    public ArrayQueue(int arrMaxSize){
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        //指向队列头部,分析出front指向队列的头的前一个位置
        front = -1;
        //指向队列尾部,队列的最后一个位置
        rear = -1;
    }
    //判断队列是否满
    public boolean isFill(){
        return rear == maxSize-1;
    }
    //判断队列是否为空
    public boolean isEmpty(){
        return rear == front;
    }
    //添加数据到队列
    public void addQueue(int n){
        //判断队列是否满
        if(isFill()){
            System.out.println("队列已满,不能加入数据~");
            return;
        }
        //让rear后移
        rear++;
        arr[rear] = n;
    }
    //获取数据
    public int getQueue(){
        //判断队列是否空
        if (isEmpty()){
            throw new RuntimeException("队列空,没有数据~");
        }
        //front 后移
        front++;
        return arr[front];
    }
    //显示队列数据
    public void show(){
        if (isEmpty()){
            System.out.println("数据是空的~~");
            return;
        }
        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];
    }
}

4.数组模拟队列的优化:数组的多次使用

package queue;

import javax.sound.midi.Soundbank;
import java.util.Scanner;

/**
 * @author りChic丶安漾
 */
public class CiecleArrayQueue {
    public static void main(String[] args) {
        //测试数组环形队列
        System.out.println("测试数组环形队列~~~");
        //设置最大数据为5,实际上最多存放4个数据
        CircleQueue queue = new CircleQueue(5);
        //接收用户输入
        char key;
        Scanner scanner = 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 = 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 CircleQueue{
    //队列最大值
    private int maxSize;
    //队列头 front指队列的第一个元素,即arr[front],   初始值:front = 0;
    private int front;
    //队列尾  rear指队列的最后一个元素的后一个位置,因为希望空出一个位置   初始值: rear = 0;
    private int rear;
    private int[] arr;

    public CircleQueue(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 = (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\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];
    }
}
单链表
  1. 单链表的创建,无序数据排序
public class SingleLinkedListDemo {
    public static void main(String[] args) {
        //创建节点
        HeroNode hero1 = new HeroNode(1, "张三", "打卡机静安寺");
        HeroNode hero2 = new HeroNode(2, "张四", "打寺");
        HeroNode hero3 = new HeroNode(3, "张无", "机静安寺");
        HeroNode hero4 = new HeroNode(4, "张留", "打卡静安寺");

        //创建链表
        SingleLinkedList singleLinkedList = new SingleLinkedList();

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~");

        singleLinkedList.addByOrder(hero1);
        singleLinkedList.addByOrder(hero4);
        singleLinkedList.addByOrder(hero3);
        singleLinkedList.addByOrder(hero2);

        singleLinkedList.list();
        //修改
        HeroNode newHeroNode = new HeroNode(2,"kd","dfd");
        singleLinkedList.upDate(newHeroNode);

        System.out.println();
        System.out.println("修改后的数据~");
        System.out.println();

        singleLinkedList.list();

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~");
        //测试删除
        singleLinkedList.delete(1);
        singleLinkedList.list();
        System.out.println("删除后的链表~");
        singleLinkedList.delete(4);
        singleLinkedList.list();
    }
}
//定义SingleLinkedList 管理
class SingleLinkedList{
    //1.初始化一个头结点,头结点不能动 , 不存放具体的数据

    private HeroNode head = new HeroNode(0,"","");

    public HeroNode getHead() {
        return head;
    }

    //添加数据到链表的尾部
    public void add(HeroNode heroNode){
        //思路:当不考虑数据的编号的顺序时
        //1.找到链表的结尾
        //2.将链表的最后一个节点的next指向下一个节点
        //head节点不能动,见一个辅助接点
        HeroNode temp = head;
        //遍历链表,找到最后一个节点
        while (true){
            //找到链表的最后
            if (temp.next == null){
                break;
            }
            //temp后移
            temp = temp.next;
        }
        //将链表最后一个节点的next指向新建的节点
        temp.next = heroNode;
    }
    //显示链表【遍历】
    public void list(){
        //判断链表是否为空
        if (head == null){
            System.out.println("链表为空!");
            return;
        }
        HeroNode temp  = head.next;
        while (true){
            if (temp == null){
                break;
            }
            System.out.println(temp);
            //将temp后移
            temp = temp.next;
        }
    }
    //第二种方式:添加数据时,进行顺序添加
    public void addByOrder(HeroNode heroNode){
        HeroNode temp = head;
        boolean flag = false;
        while (true){
            //说明已到链表最后
            if (temp.next == null){
                break;
            }
            //说明找到插入位置
            if (temp.next.no > heroNode.no){
                break;
                //说明插入的数据的编号已存在
            }else if (temp.next.no == heroNode.no){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag){
            System.out.printf("所插入数据的编号 %d 已存在\n" , temp.next.no);
        }else {
            //插入到链表中
            heroNode.next = temp.next;
            temp.next = heroNode;
        }
    }
    //修改信息
    public void upDate(HeroNode newHeroNode){
        //判断链表是否为空
        if (head.next == null){
            System.out.println("链表为空!");
            return;
        }
        HeroNode temp = head.next;
        boolean flag = false;
        while (true){
            if (temp.next == null){
                break;
            }
            if (temp.no == newHeroNode.no){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        //根据 flag 进行判断是否有数据
        if (flag){
            temp.name = newHeroNode.name;
            temp.nickname = newHeroNode.nickname;
        }else {
            System.out.printf("没有找到编号 %d 对应的节点!\n",newHeroNode.no);
        }
    }
    //单链表的删除
    public void delete(int no){
        HeroNode temp = head;
        boolean flag = false;
        while (true){
            if (temp.next == null){
                break;
            }
            if (temp.next.no == no){
                flag = true;
                break;
            }
            temp = temp.next;
        }
        if (flag){
            temp.next = temp.next.next;
        }else {
            System.out.printf("要删除的节点 %d 不存在",no);
        }
    }
}


//定义HeroNode,每一个HeroNode都是一个节点
class HeroNode{
    public int no;
    public String name;
    public String nickname;
    //指向下一个节点
    public HeroNode next;

    //构造器
    public HeroNode(int no , String name , String nickname){
        this.no = no;
        this.name = name;
        this.nickname = nickname;

    }

    @Override
    public String toString() {
        return "HeroNode [no = " + no + " ] [name = " + name + " ] [nickname = " + nickname + " ]";
    }
}
  1. 单链表的应用(面试题)
import java.util.Stack;

/**
 * @author りChic丶安漾
 */
public class SingleLinkedListDemo {
    public static void main(String[] args) {
        //创建节点
        HeroNode hero1 = new HeroNode(1, "张三", "打卡机静安寺");
        HeroNode hero2 = new HeroNode(2, "张四", "打寺");
        HeroNode hero3 = new HeroNode(3, "张无", "机静安寺");
        HeroNode hero4 = new HeroNode(4, "张留", "打卡静安寺");

        //创建链表
        SingleLinkedList singleLinkedList = new SingleLinkedList();

        //测试单链表的有效节点
        System.out.println(getLength(singleLinkedList.getHead()));
        System.out.println("~~~~~~~~~~~~~");
        
        //找到单链表的倒数第k个节点
        HeroNode res = findLastIndexNode(singleLinkedList.getHead(),1);
        System.out.println(res);

        //测试单链表的反转
        reversetList(singleLinkedList.getHead());
        singleLinkedList.list();
        
        //测试单链表的逆序打印,不破坏链表结构
        reverseNode(singleLinkedList.getHead());

    }
    
    //单链表的逆序打印,不破坏链表结构
    public static void reverseNode(HeroNode head){
        if (head.next ==null){
            return;
        }
        HeroNode temp = head.next;
        Stack<HeroNode> heroNodes = new Stack<>();
        while (temp != null){
            heroNodes.push(temp);
            temp = temp.next;
        }
        while (heroNodes.size() > 0){
            System.out.println(heroNodes.pop());
        }
    }

    //实现单链表的反转
    public static void reversetList(HeroNode head){
        //判断链表是否为空或者只有一个节点
        if (head.next == null || head.next.next == null){
            return;
        }
        //定义一个辅助变量方便遍历单链表
        HeroNode temp = head.next;
        HeroNode next = null; // 指向当前节点[temp]的下一个节点
        HeroNode reverseNode = new HeroNode(0,"","");
        //重点:
        while (temp != null){
            next = temp.next;
            temp.next = reverseNode.next;
            reverseNode.next = temp;
            temp = next;
        }
        head.next = reverseNode.next;
    }

    //获取单链表的倒数第k个节点
    public static HeroNode findLastIndexNode(HeroNode head , int index){
        //判断是否为空
        if (head.next == null){
            return null;
        }
        //遍历链表,得到链表的长度
        int size = getLength(head);
        //用for循环得到倒数的k个节点  size - index
        HeroNode temp = head.next;
        for (int i = 0; i < size - index; i++) {
            temp = temp.next;
        }
        return temp;
    }

    //获取单链表有效节点的个数
    public static int getLength(HeroNode head){
        //空链表
        if (head.next == null){
            return 0;
        }
        int length = 0;
        //
        HeroNode cur = head.next;
        while (cur != null){
            length++;
            cur = cur.next;
        }
        return length;
    }
}

//定义SingleLinkedList 管理
class SingleLinkedList{
    //1.初始化一个头结点,头结点不能动 , 不存放具体的数据

    private HeroNode head = new HeroNode(0,"","");

    public HeroNode getHead() {
        return head;
    }
    //显示链表【遍历】
    public void list(){
        //判断链表是否为空
        if (head == null){
            System.out.println("链表为空!");
            return;
        }
        HeroNode temp  = head.next;
        while (true){
            if (temp == null){
                break;
            }
            System.out.println(temp);
            //将temp后移
            temp = temp.next;
        }
    }
}


//定义HeroNode,每一个HeroNode都是一个节点
class HeroNode{
    public int no;
    public String name;
    public String nickname;
    //指向下一个节点
    public HeroNode next;

    //构造器
    public HeroNode(int no , String name , String nickname){
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }
    @Override
    public String toString() {
        return "HeroNode [no = " + no + " ] [name = " + name + " ] [nickname = " + nickname + " ]";
    }
}
  • 合并两个有序的单链表,合并后的链表依然有序
  • [ 思路 ]
  • 1.创建一个新的空链表做为合并后的新链表容器
    
  • 2.将原来的两个两边按照大小分别移至新联表中
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

? Adore ?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值