首页 > 解决方案 > 如何修复代码中的入队和出队问题?

问题描述

我正在研究这个项目,以使用 Java 中的队列来解决迷宫问题。当我在主课上工作时,我在入队和出队方法中特别遇到了错误。

public void mazeSolver(int startRow, int startCol, int endRow, int endCol) { 
    Location location = new Location();
    location.setPosition(startRow, startCol);
    LocationQueue queue = new LocationQueue();
    queue.enqueue(location);
    while (!queue.isEmpty()) {
        location = queue.dequeue();
        mazeArray[location.getRow()][location.getColumn()] = '.';
        if ((location.getRow() == endRow && location.getColumn() == endCol)) {
            break;
        }
        if (location.getRow() + 1 < Rows) {
            if (mazeArray[location.getRow() + 1][location.getColumn()] == ' ') {
                Location newLocation = new Location();
                newLocation.setPosition(location.getRow() + 1, location.getColumn());
                queue.enqueue(newLocation);
            }
        }
        if (location.getRow() - 1 >= 0) {
            if (mazeArray[location.getRow() - 1][location.getColumn()] == ' ') {
                Location newLocation = new Location();
                newLocation.setPosition(location.getRow() - 1, location.getColumn());
                queue.enqueue(newLocation);
            }
        }
        if (location.getColumn() + 1 < Columns) {
            if (mazeArray[location.getRow()][location.getColumn() + 1] == ' ') {
                Location newLocation = new Location();
                newLocation.setPosition(location.getRow(), location.getColumn() + 1);
                queue.enqueue(newLocation);
            }
        }
        if (location.getColumn() - 1 > 0) {
            if (mazeArray[location.getRow()][location.getColumn() - 1] == ' ') {
                Location newLocation = new Location();
                newLocation.setPosition(location.getRow(), location.getColumn() - 1);
                queue.enqueue(newLocation);
            }
        }
    }
}

我有一个 LocationQueue 类,它涉及入队和出队方法:

public class LocationQueue<Location> {

LinkList locationList = new LinkList();

public void enqueue(int iData) {
    locationList.addLast(iData);
}

public Node dequeue() {
    if (!locationList.isEmpty()) {
        return locationList.deleteFirst();
    } else {
        return null;
    }
}

public void displayQueue() {
    locationList.displayList();
    System.out.println();
}

public boolean isEmpty() {
    return locationList.isEmpty();
}
}

这是我的节点类:

public class Node  {
int iData;
Node next;

public Node (int values) {
    iData = values;
    next = null;
}

  public void displayNode(){
        System.out.print(iData + " ");
    }
}

这个问题可能是一个简单的修复,我还没有发现我做错了什么。由于错误说明“LocationQueue 类型中的方法 enqueue(int) 不适用于参数 (Location)”和“类型不匹配:无法从节点转换为位置”。我只是不确定我需要更改代码的哪一部分。我的 Location 和 LinkList 类可能与在此问题中发布无关,但是如果您想查看这两个类,我不介意发布它。

注意:如果我的代码格式看起来有点不对劲,我很抱歉。我仍然习惯于格式化 StackOverflow 上的代码。

标签: javaqueueenqueuenodequeue

解决方案


推荐阅读