java 队列的实现

Java中提供了Queue队列接口,可以继承此接口实现队列的数据结构,Java中提供了以下实现类,可以根据需要选择合适的队列

@see LinkedList
@see PriorityQueue
@see java.util.concurrent.LinkedBlockingQueue
@see java.util.concurrent.BlockingQueue
@see java.util.concurrent.ArrayBlockingQueue
@see java.util.concurrent.LinkedBlockingQueue
@see java.util.concurrent.PriorityBlockingQueue

使用LinkedList作为队列:

/**
 * java 基于LinkedList为底层实现的队列   (栈也可以)
 * @author Linging
 * @date 2019/2/10
 * 
 */

public class CollectionQueue {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Queue<String> que = new LinkedList<String>();
		
		//将指定元素插入到队尾
		que.offer("a");
		que.offer("b");
		que.offer("c");
		
		//检索,但不移除队列的头,如果队列为空则返回null
		System.out.println(que.peek());
		
		//检索,但不移除队列的头,如果队列为空则会抛出一个异常
		System.out.println(que.element());
		
		//检索并移除此队列的头,如果队列为空,则返回 null
		System.out.println(que.poll());
		
		//检索并移除此队列的头,如果队列为空,则会抛出一个异常
		System.out.println(que.remove());
		
		//打印队列元素
		System.out.println(que.toString());
		
		//打印队列元素
		while(!que.isEmpty()) {
			System.out.println(que.poll());
		}
		
	}

}

可根据需求自行封装方法。

学习自:https://blog.csdn.net/D578332749/article/details/80818613

  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值