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

时间:2019-05-28 11:30:24

标签: java linked-list testcase

我正在尝试编写一个函数以返回Java列表中节点的数量。

我有一个类名Waypoint,它定义了该点和其他名为TourElement的类。 TourElement用于创建包含点的节点。

// Waypoint

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());
    }

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

2 个答案:

答案 0 :(得分:0)

条件(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;
}

答案 1 :(得分:0)

考虑到这是一项家庭作业,我将给您一些有关如何解决问题的提示。在getNoOfWaypoints()中,每次都会检查电流,但永远不会更新。

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