我如何计算 java 中节点列表结构的总数

how I can count the total number of nodes List Structures in java

我正在尝试编写一个函数来 return java 中列表中的节点数。

我有一个 class 名称航路点,它定义了点和其他 class 命名的 TourElement。 TourElement 用于创建包含点的节点。

//航点

public class Waypoint {
    int x  ;
    int y  ;
    public int getX()
    {
        return this.x;
    }
    public int getY()
    {
        return this.y;
    }
    public void setXY(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

//游览元素

public class TourElement {
 private Waypoint points;
 private TourElement next;
  public void setWaypoint( Waypoint points)
 {
   this.points = points; 
 }
  public void setTourElement(TourElement next)
  {
      this.next = next;
  }
 Waypoint getWaypoint()
 {
     return this.points;
 }

 TourElement getNext()
 {
     return this.next;
 }

// 我在使用 getNoOfWaypoints() 方法时遇到了一些问题,我的代码有什么问题吗?。我的方法没有通过测试用例:

int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
    }
    return count;
}

//我老师提供的测试用例

  private Waypoint createWaypoint(int x, int y) {
        Waypoint wp = new Waypoint();
        wp.setXY(x, y);
        return wp;
    }


    private TourElement createElementList(int[][] waypoints){
        assert waypoints.length > 0;
        TourElement elem = new TourElement();
        int lastIndex = waypoints.length-1;
        Waypoint wp = createWaypoint(waypoints[lastIndex][0], waypoints[lastIndex][1]);
        elem.setWaypoint(wp);
        for (int i = lastIndex-1; i >= 0 ; i--) {
            wp = createWaypoint(waypoints[i][0], waypoints[i][1]);
            elem = elem.addStart(wp);
        }
        return elem;
    }



public void testGetNoOfWaypoints_NotChangingList() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        int unused = elem.getNoOfWaypoints();

        assertArrayEquals(new int[] {0, 0}, elem.getWaypoint().toArray());
        assertArrayEquals(new int[] {1, 1}, elem.getNext().getWaypoint().toArray());
        assertArrayEquals(new int[] {2, 2}, elem.getNext().getNext().getWaypoint().toArray());
        assertNull(elem.getNext().getNext().getNext());
    }

我不知道我的输出有什么问题。我真的很想知道如何通过测试用例。请帮我弄清楚。非常感谢你!!

条件 (current.next != null) 将始终为 false 或始终为 true,因为您永远不会在循环内修改 current

应该是:

int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
        current = current.next;
    }
    return count;
}

考虑到这是一项作业,我会给你一些提示,告诉你如何解决这个问题。在 getNoOfWaypoints() 中,每次都会检查电流,但它永远不会更新。

int getNoOfWaypoints()
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        System.out.println(count);
    }
    return count;
}