有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在java中,如何从具有给定索引的链表中获取元素?

我正在学习Java中的链接列表。我想写一个方法,根据给定的索引给出node的值

我写了一个函数,但它没有通过一些测试用例,我不知道为什么?。我的逻辑有什么问题

//航路点。爪哇

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

int getNoOfWaypoints()//  return the number of waypoints in the list
{
    int count = 1;
    TourElement current = getNext();
    while(current.next != null)
    {
        count++;
        current = current.next;
        System.out.println(count);
    }
    return count;
} 

//下面是我正在尝试的方法:

Waypoint getWaypointAt(int index)
{
   int totalElement = getNoOfWaypoints();
   int count = 0;
   TourElement current = getNext();
   if(index < totalElement && index >= 0)
   {
       while (current.next != null)
      {
        if(count == index)
          {
              return getWaypoint();
          }
         count++;
          current = current.next;
         }

       }
   return null;
}

//测试用例: //案例1:通行证

public void test0GetWaypointAt_First() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(0, 0);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(0).toArray());
    }

//案例2和案例3:失败

public void test0GetWaypointAt_Snd() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(1, 1);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(1).toArray());
    }

    @Test
    public void test0GetWaypointAt_Last() {
        TourElement elem = createElementList(new int[][] {{0, 0}, {1, 1}, {2, 2}});
        Waypoint expected = createWaypoint(2, 2);
        assertArrayEquals(expected.toArray(), elem.getWaypointAt(2).toArray());
    }

我不知道原因。请帮帮我。事先非常感谢


共 (1) 个答案

  1. # 1 楼答案

    您用list构建的结构似乎还可以,关于您的方法getWaypointAt我发现至少有两个问题:

    第一个问题

       TourElement current = getNext();
    

    getNext()已经是列表中的下一个元素,因此您一直在跳过第一个元素。应该是

       TourElement current = this;
    

    第二个问题

        return getWaypoint();
    

    它始终从头部返回航路点。应该是

        return current.getWaypoint();
    

    看来你的第一次考试也应该不及格。我看不出在createElementList中构建元素的方式,这可能是它通过的原因之一