java队列实现

1、重写toString

package 队列的实现;

public class List {
    public String name;
    public List(){

    }
    public List(String name){
        this.name=name;
    }
    //重写toString
    public String toString(){
        return name;
    }
}

实现

package 队列的实现;
import java.util.LinkedList;
import java.util.Queue;

public class QueueList {
    public static void main(String []args){

        //定义Queue接口
        Queue<List> q = new LinkedList<>();
        //初始化
        for (int i = 1; i <= 10; i++) {
            q.offer(new List("第"+i+"个元素"));
        }
        System.out.println("-------------------输出数据---------------------------");
        //输出数据
        System.out.println(q);
        System.out.println("-------------------查看第一个元素,不会在队列中删除---------------------------");
        //查看第一个元素
        System.out.println(q.peek());
        System.out.println("-------------------取出第一个元素,会把元素删除---------------------------");
        //取出第一个元素
        System.out.println(q.poll());
        System.out.println("-------------------输出删除后的数据---------------------------");
        //输出数据
        System.out.println(q);
    }
}

执行结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用 Java 队列实现迷宫寻路的示例代码: ```java import java.util.LinkedList; import java.util.Queue; public class MazeSolver { private int[][] maze; private int[] start; private int[] end; private Queue<int[]> queue; public MazeSolver(int[][] maze, int[] start, int[] end) { this.maze = maze; this.start = start; this.end = end; this.queue = new LinkedList<>(); this.queue.offer(start); } public int[][] solve() { while (!queue.isEmpty()) { int[] current = queue.poll(); int x = current[0]; int y = current[1]; if (x == end[0] && y == end[1]) { return maze; } // 上下左右四个方向 int[][] directions = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}}; for (int[] dir : directions) { int nextX = x + dir[0]; int nextY = y + dir[1]; // 判断是否越界、是否是障碍物、是否已经走过 if (nextX >= 0 && nextX < maze.length && nextY >= 0 && nextY < maze[0].length && maze[nextX][nextY] == 0) { maze[nextX][nextY] = maze[x][y] + 1; queue.offer(new int[]{nextX, nextY}); } } } return null; // 无解情况 } } ``` 在上述代码中,我们使用了一个二维数组 `maze` 来表示迷宫,其中 `0` 表示可走的路,`1` 表示障碍物。`start` 和 `end` 分别表示起点和终点的坐标。 我们使用一个队列 `queue` 来存储待访问的节点,初始时将起点加入队列中。然后在每次取出队列中的节点进行访问时,我们遍历其上下左右四个方向,并判断下一个节点是否满足可访问的条件(不越界、不是障碍物、未走过),如果满足条件,则将其加入队列,并将其值更新为当前节点的值加一。 最终,如果队列为空,说明无解;否则,返回更新后的 `maze` 数组即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

凌晨四点半的太阳111

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

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

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

打赏作者

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

抵扣说明:

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

余额充值