Java数据结构之栈、队列

java 线性数据结构
java 数据结构之 stack

public class Stack {
    private int[] elements;
    public  Stack(){
        elements=new int[0];
    }
    //实现入栈与出栈
    public void add(int value){     //栈中添加元素
        int[] newArr=new int[elements.length+1];
        for (int i = 0; i <elements.length ; i++) {
            newArr[i]=elements[i];

        }
        newArr[elements.length]=value;
        elements=newArr;
    }
    public  void show(){  //展示栈中的元素
        for (int i = 0; i <elements.length ; i++) {
            System.out.println(elements[i]);
        }
    }
    public void pop(){  //取出栈顶元素
        int[] newArr=new int[elements.length-1];
        int stackTop=elements[elements.length-1];
        for (int i = 0; i <elements.length-1 ; i++) {
          newArr[i]=elements[i];
        }
        elements=newArr;
        System.out.println("取出的栈顶元素是:"+stackTop);
    }
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
迷宫问题是一个经典的算法问题,可以使用Java中的数据结构栈和队列来解决。下面是一个使用栈和队列解决迷宫问题的示例代码: ```java import java.util.*; public class MazeSolver { private static final int[][] DIRECTIONS = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; // 上下左右四个方向 public static boolean solveMaze(int[][] maze, int startX, int startY, int endX, int endY) { int rows = maze.length; int cols = maze[0].length; boolean[][] visited = new boolean[rows][cols]; // 记录是否访问过 visited[startX][startY] = true; Stack<int[]> stack = new Stack<>(); // 使用栈来进行深度优先搜索 stack.push(new int[]{startX, startY}); while (!stack.isEmpty()) { int[] curr = stack.pop(); int currX = curr[0]; int currY = curr[1]; if (currX == endX && currY == endY) { return true; // 找到终点 } for (int[] dir : DIRECTIONS) { int nextX = currX + dir[0]; int nextY = currY + dir[1]; if (nextX >= 0 && nextX < rows && nextY >= 0 && nextY < cols && maze[nextX][nextY] == 0 && !visited[nextX][nextY]) { stack.push(new int[]{nextX, nextY}); visited[nextX][nextY] = true; } } } return false; // 无法找到路径 } public static void main(String[] args) { int[][] maze = { {0, 1, 0, 0, 0}, {0, 1, 0, 1, 0}, {0, 0, 0, 0, 0}, {0, 1, 1, 1, 0}, {0, 0, 0, 1, 0} }; int startX = 0; int startY = 0; int endX = 4; int endY = 4; boolean canSolve = solveMaze(maze, startX, startY, endX, endY); System.out.println("Can solve maze: " + canSolve); } } ``` 这段代码使用了一个二维数组来表示迷宫,其中0表示可以通过的路径,1表示墙壁。通过深度优先搜索的方式,使用栈来记录路径,直到找到终点或者无法找到路径为止。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值