数据结构与算法

数据结构与算法

诺塔游戏:

请完成汉诺塔游戏的代码: 要求:1) 将 A 塔的所有圆盘移动到 C 塔。并且规定,在 2) 小圆盘上不能放大圆盘, 3)在三根柱子之间一次只能移动一个圆盘

八皇后问题

八皇后问题,是一个古老而著名的问题,是回溯算法的典型案例。该问题是国际西洋棋棋手马克斯·贝瑟尔于 1848 年提出:在 8×8 格的国际象棋上摆放八个皇后,使其不能互相攻击,即:任意两个皇后都不能处于同一行、 同一列或同一斜线上,问有多少种摆法。【92】=> 分治算法

马踏棋盘算法

介绍和游戏演示 1) 马踏棋盘算法也被称为骑士周游问题 2) 将马随机放在国际象棋的 8×8 棋盘 [0~7][0~7]的某个方格中,马按走棋规则(马走日字)进行移动。要求 每个方格只进入一次,走遍棋盘上全部 64 个方格

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

  2. 线性结构有两种不同的存储结构,即顺序存储结构(数组)和链式存储结构(链表)。顺序存储的线性表称为顺序 表,顺序表中的存储元素是连续的

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

非线性结构

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

稀疏数组

稀疏数组的处理方法是:

  1. 记录数组一共有几行几列,有多少个不同的值 。把具有不同值的元素的行列及值记录在一个小规模的数组中,从而缩小程序的规模
二维数组转稀疏数组:
1 遍历原始的二维数组,得到有效数据的个数sum 
2.根据sum创建稀疏数组sparseArr int[sum+1][3]
3.将二维数组的有效数据存入稀疏数组。
稀疏数组转原始二维数组:
1.读取稀疏数组第一行,根据数据创建二维数组。
2.读取稀疏数组后几行的数据,还原二维数组。
public static void main(String[] args) throws IOException {
        //创建二维数组11*11 0表示无棋子,1黑子 2蓝子
        int chessArr1[][]=new int[11][11];
        chessArr1[1][2]=1;
        chessArr1[2][3]=2;
        //输出原始二维数组
        for (int[] row:chessArr1){
            for (int data:row){
                System.out.print(data+"\t");
            }
            System.out.println();
        }

        //将二维数组转为稀疏数组,遍历二维数组,获得非0的个数
        int sum=0;
        for (int i=0;i<11;i++){
            for (int j=0;j<11;j++){
                if (chessArr1[i][j]!=0){
                    sum++;
                }
            }
        }
        int sparseArr[][]=new int[sum+1][3];
        //给稀疏数组赋值 第一行输入
        sparseArr[0][0]=11;
        sparseArr[0][1]=11;
        sparseArr[0][2]=sum;

        //遍历二维数组,将非0的储存放到sparseArr中
        int count=0;//用于记录是第几个非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];
                }
            }
        }
        //输出稀疏数组的形式
        System.out.println("稀疏数组");
        for (int i=0;i<sparseArr.length;i++){
            System.out.println(sparseArr[i][0]+"\t"+sparseArr[i][1]+"\t"+sparseArr[i][2]);
        }
        System.out.println();

        //将稀疏数组保存到文件中
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("src\\txtwj\\java.txt")))) {
            for (int[] row : sparseArr) {
                for (int data : row) {
                    bw.write(data);
                    bw.newLine();
                    bw.flush();
                }
            }
        }

        //读取稀疏数组,组成二维数组  长度为稀疏数组的00 01 读取稀疏数组从第二行开始
        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];
        }
        for (int i=0;i<chessArr2.length;i++){
            for (int j=0;j<chessArr2[i].length;j++){
                System.out.print(chessArr2[i][j]+"\t");
            }
            System.out.println();
        }
    }
队列
  1. 队列是一个有序列表,可以用数组或是链表来实现。

  2. 遵循先入先出的原则。即:先存入队列的数据,要先取出。后存入的要后取出

1.目前数组使用一次就不能用, 没有达到复用的效果

  1. 将这个数组使用算法,改进成一个环形的队列 取模:%
public static void main(String[] args) {
    ArrayQueue array=new ArrayQueue(3);
    char key=' ';//接受用户输入
    Scanner sc=new Scanner(System.in);
    boolean loop =true;
    //输出一个菜单
    while (loop){
        System.out.println("s:显示队列");
        System.out.println("e:退出程序");
        System.out.println("a:添加数据");
        System.out.println("g:取出数据");
        System.out.println("h:查看队列头数据");
        key=sc.next().charAt(0);//接受一个字符
        switch (key){
            case 's':
                array.showQueue();  break;
            case 'a':
                System.out.println("输入一个数据");
                int number = sc.nextInt();
                array.addQueue(number);
                break;
            case 'g':
                try{
                    int res= array.getQueue();
                    System.out.println("取出的数据是:"+res);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                break;
            case 'h':
                try{
                    int res=array.headQueue();
                    System.out.println("数据头是:"+res);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                break;
            case 'e':sc.close();  //关闭Scanner
            loop=false;
        }
    }
}

static class ArrayQueue{
    private final int maxSize;//队列的最大容量
    private int front;//队列头
    private int rear;//队列尾
    private final 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 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()){
            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];
    }
}
数组模拟环形数组

Java Queue常用方法

(1)获取头元素的方法

①poll()获取并移出队列的头,如果次队列为空,则返回null。

②remove()获取并移出此队列的头,如果此队列为空则抛出NoSuchElementException异常

(2)获取但是不移除

①peek()获取队列的头,但是不移除队列的头,如果次队列为空,则返回null。

②element()获取队列的头,但是不移除队列的头,如果队列为空,则将跑出NoSuchElementException异常。

(3)添加元素的方法

offer()将指定的元素插入此队列(如果立即可行且不会违反容量限制),插入成功返回true,否则返回false。当使用有容量限制的队列时offer()方法通常优于add()方法------add()方法可能无法插入元素,而是抛出一个IllegalStateException异常。

add()将制定的元素插入此队列。

对前面的数组模拟队列的优化,充分利用数组. 因此将数组看做是一个环形的。(通过取模的方式来实现即可)

  1. 尾索引的下一个为头索引时表示队列满,即将队列容量空出一个作为约定,

这个在做判断队列满的 时候需要注意 (rear + 1) % maxSize == front [满]

  1. rear == front [空]

取模

public static void main(String[] args) {
    ArrayQueue array=new ArrayQueue(4);
    char key=' ';//接受用户输入
    Scanner sc=new Scanner(System.in);
    boolean loop =true;
    //输出一个菜单
    while (loop){
        System.out.println("s:显示队列");
        System.out.println("e:退出程序");
        System.out.println("a:添加数据");
        System.out.println("g:取出数据");
        System.out.println("h:查看队列头数据");
        key=sc.next().charAt(0);//接受一个字符
        switch (key){
            case 's':
                array.showQueue();  break;
            case 'a':
                System.out.println("输入一个数据");
                int number = sc.nextInt();
                array.addQueue(number);
                break;
            case 'g':
                try{
                    int res= array.getQueue();
                    System.out.println("取出的数据是:"+res);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                break;
            case 'h':
                try{
                    int res=array.headQueue();
                    System.out.println("数据头是:"+res);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                break;
            case 'e':sc.close();  //关闭Scanner
                loop=false;
        }
    }
}

static class ArrayQueue {
    private final int Maxsize;
    private int front;
    private int rear;
    private final int[] arr;

    ArrayQueue(int size) {
        Maxsize = size;
        arr = new int[Maxsize];
        front = 0;
        rear = 0;
    }

    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;
        //当rear达到最后一个时,即rear变成0,组成一个循环
    }
    public int getQueue(){
        if (isempty()){
            throw new RuntimeException("队列为空,无法取出数据!");
        }
        int temp=arr[front];
        //取模
        front=(front+1)%Maxsize;
        return temp;
    }
    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 headQueue(){
        //判断 为空则无数据
        if (isempty()){
            throw new RuntimeException("队列为空,无数据!");
        }
        return arr[front];
    }
    //队列中的有效数据
    public int size(){
        return (rear+Maxsize-front)%Maxsize;
    }
}
链表
  1. 链表是以节点的方式来存储,是链式存储

  2. 每个节点包含 data 域,next 域:指向下一个节点.

  3. 如图:发现链表的各个节点不一定是连续存储.

  4. 链表分带头节点的链表和没有头节点的链表,根据实际的需求来确定

单向链表

每个节点Node的next指向下一个节点。当next为null,则为链表的最后一个。

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 hero=new SingleLinkedList();
    hero.add(hero1);
    hero.add(hero2);
    hero.add(hero3);
    hero.add(hero4);
    hero.show();

}
//定义个一个SingleLinkedList,管理链表
static class SingleLinkedList{
    //初始化头节点  头节点不做改变
    private final HeroNode head = new HeroNode(0," "," ");

    //添加节点到链表中 :找到当前链表的最后一个节点,将最后节点的next,指向新的节点
    public void add(HeroNode heroNode){
        //需要一个辅助变量 temp 用于遍历链表,找节点的next
        HeroNode temp=head;
        //遍历链表,找到最后
        while (true){
            //找链表的最后一个节点的next,当temp为最后一个节点时,退出循环。
            if (temp.next==null){
                break;
            }
            //如果不是最后一个节点,就让temp指向下一个节点
            temp=temp.next;
        }

        //当temp为最后一个节点时,让temp指向新的节点
        temp.next=heroNode;
    }
    //显示链表,通过遍历
    public void show(){
        //头节点的next为空,则链表为空
        if (head.next==null){
            System.out.println("链表为空");
            return;
        }
        //遍历需要一个辅助变量来遍历
        HeroNode temp=head.next;
        for (;;){
            //判断是否到链表最后
            if (temp.next==null){
                break;
            }
            //不到最后则输出节点
            System.out.println(temp);
            //将temp后移,变量下一个
            temp=temp.next;
        }
    }
}
//定义HeroNode,每个HeroNode对象就是一个节点。
static class HeroNode{
    public int no;
    public String name;
    public String nickname;
    public HeroNode next;//指向下一个节点

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

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickname='" + nickname + '\'' +
                "" +
                '}';
    }
}

将no作为排名顺序:

第二种方式在添加英雄时,根据排名将英雄插入到指定位置 //(如果有这个排名,则添加失败,并给出提示。

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 hero=new SingleLinkedList();
        hero.twoadd(hero1);
        hero.twoadd(hero4);
        hero.twoadd(hero3);
        hero.twoadd(hero2);
        hero.show();

    }
    //定义个一个SingleLinkedList,管理链表
    static class SingleLinkedList{
        //初始化头节点  头节点不做改变
        private final HeroNode head = new HeroNode(0," "," ");

        //添加节点到链表中 :找到当前链表的最后一个节点,将最后节点的next,指向新的节点
        public void add(HeroNode heroNode){
            //需要一个辅助变量 temp 用于遍历链表,找节点的next
            HeroNode temp=head;
            //遍历链表,找到最后
            while (true){
                //找链表的最后一个节点的next,当temp为最后一个节点时,退出循环。
                if (temp.next==null){
                    break;
                }
                //如果不是最后一个节点,就让temp指向下一个节点
                temp=temp.next;
            }

            //当temp为最后一个节点时,让temp指向新的节点
            temp.next=heroNode;
        }

        //第二种添加方式:根据no的排名,将节点插入指定位置,如果已经存在这个no,则添加失败,给出提示
        public  void twoadd(HeroNode heroNode){
             //因为头节点不能动,因此我们仍然通过一个辅助指针来帮助找到添加的位置
            //因为为单链表,所有我们找到的temp是位于添加位置的前一个节点,否则无法插入
            HeroNode temp=head;
            boolean flag=false;// flag标识添加的编号是否存在
            while (true){
                if (temp.next==null){
                    break;
                }
                if (temp.next.no> heroNode.no){  //位置找到,就在temp后面插入
                    break;
                }else if (temp.next.no==heroNode.no){ //说明希望添加的heroNode的编号已经存在
                    flag=true;
                    break;
                }
                temp=temp.next;
            }
            //判断flag的值
            if (flag){  //true 节点已经存在,不能添加
                System.out.println("编号已经存在,不能添加");
            }else {
                //插入到temp后面
                heroNode.next=temp.next;
                temp.next=heroNode;
            }
        }
        //显示链表,通过遍历
        public void show(){
            //头节点的next为空,则链表为空
            if (head.next==null){
                System.out.println("链表为空");
                return;
            }
            //遍历需要一个辅助变量来遍历
            HeroNode temp=head.next;
            for (;;){
                //不到最后则输出节点
                System.out.println(temp);
                //判断是否到链表最后
                if (temp.next==null){
                    break;
                }
                //将temp后移,变量下一个
                temp=temp.next;
            }
        }
    }
    //定义HeroNode,每个HeroNode对象就是一个节点。
    static class HeroNode{
        public int no;
        public String name;
        public String nickname;
        public HeroNode next;//指向下一个节点

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

        @Override
        public String toString() {
            return "HeroNode{" +
                    "no=" + no +
                    ", name='" + name + '\'' +
                    ", nickname='" + nickname + '\'' +
                    "" +
                    '}';
        }
    }

更改与删除

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 hero=new SingleLinkedList();
    hero.twoadd(hero1);
    hero.twoadd(hero4);
    hero.twoadd(hero3);
    hero.twoadd(hero2);
    hero.show();

    System.out.println();
    HeroNode hero5=new HeroNode(2,"卢姥爷","伞兵一号");
    hero.update(hero5);
    hero.show();

    System.out.println();
    hero.delete(hero1.no);
    hero.show();

}
//定义个一个SingleLinkedList,管理链表
//temp=temp.next 相当于i++
static class SingleLinkedList{
    //初始化头节点  头节点不做改变
    private final HeroNode head = new HeroNode(0," "," ");

    //添加节点到链表中 :找到当前链表的最后一个节点,将最后节点的next,指向新的节点
    public void add(HeroNode heroNode){
        //需要一个辅助变量 temp 用于遍历链表,找节点的next
        HeroNode temp=head;
        //遍历链表,找到最后
        while (true){
            //找链表的最后一个节点的next,当temp为最后一个节点时,退出循环。
            if (temp.next==null){
                break;
            }
            //如果不是最后一个节点,就让temp指向下一个节点
            temp=temp.next;
        }

        //当temp为最后一个节点时,让temp指向新的节点
        temp.next=heroNode;
    }

    //第二种添加方式:根据no的排名,将节点插入指定位置,如果已经存在这个no,则添加失败,给出提示
    public  void twoadd(HeroNode heroNode){
         //因为头节点不能动,因此我们仍然通过一个辅助指针来帮助找到添加的位置
        //因为为单链表,所有我们找到的temp是位于添加位置的前一个节点,否则无法插入
        HeroNode temp=head;
        boolean flag=false;// flag标识添加的编号是否存在
        while (true){
            if (temp.next==null){
                break;
            }
            if (temp.next.no> heroNode.no){  //位置找到,就在temp后面插入
                break;
            }else if (temp.next.no==heroNode.no){ //说明希望添加的heroNode的编号已经存在
                flag=true;
                break;
            }
            temp=temp.next;  //相当于temp++;
        }
        //判断flag的值
        if (flag){  //true 节点已经存在,不能添加
            System.out.println("编号已经存在,不能添加");
        }else {
            //插入到temp后面
            heroNode.next=temp.next;
            temp.next=heroNode;
        }
    }
    //根据no编号来修改
    public void update(HeroNode newHeroNode){
        //判断是否为空
        if (head.next==null){
            System.out.println("链表为空");
            return;
        }
        //找到需要修改的节点,根据no编号
        //定义一个辅助变量
        HeroNode temp=head.next;
        boolean flag=false;  //表示是否找到节点
        while (true){
            if (temp==null){
                break;
            }
            if (temp.no== newHeroNode.no){
                flag=true;
                break;
            }
            temp=temp.next;
        }
        if (flag){  //如果flag为true,就把新的HeroNode赋值给temp,temp在赋值给原来的HeroNode
            temp.name= newHeroNode.name;
            temp.nickname= newHeroNode.nickname;;
        }else {
            System.out.println("没有找到这编号的节点");
        }

    }
    //head不动,找一个temp的辅助节点去指向被删除节点的前一个节点,并让前一个节点指向被删除的后一个节点
    public void delete(int no){
        HeroNode temp=head;
        boolean flag=false;  //标志是否找到待删除的节点

        while (true){
            if (temp.next==null){
                break;
            }
            if (temp.next.no==no){ //输入的编号 为temp的下一个编号编号相同,则为待删除编号
                flag=true;
                break;
            }
            temp=temp.next;
        }
        if (flag){  //flag为true则为找到待删除节点
            temp.next=temp.next.next;
        }else {
            System.out.println("没有找到要删除的节点");
        }
    }
    //显示链表,通过遍历
    public void show(){
        //头节点的next为空,则链表为空
        if (head.next==null){
            System.out.println("链表为空");
            return;
        }
        //遍历需要一个辅助变量来遍历
        HeroNode temp=head.next;
        for (;;){
            //不到最后则输出节点
            System.out.println(temp);
            //判断是否到链表最后
            if (temp.next==null){
                break;
            }
            //将temp后移,变量下一个
            temp=temp.next;
        }
    }
}
//定义HeroNode,每个HeroNode对象就是一个节点。
static class HeroNode{
    public int no;
    public String name;
    public String nickname;
    public HeroNode next;//指向下一个节点

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

    @Override
    public String toString() {
        return "HeroNode{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickname='" + nickname + '\'' +
   
  • 41
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值