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

时间:2019-05-28 14:34:35

标签: java linked-list nodes

我正在学习Java中的链接列表。并且我想写一个方法来根据给定的索引给出节点的值

我编写了一个函数,但是它没有通过一些测试用例,并且我不知道为什么?我的逻辑怎么了?

// waypoint.java

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

// TourElement.java

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 个答案:

答案 0 :(得分:1)

关于列表getWaypointAt的方法,用列表构建的结构似乎还可以,至少有两个问题:

第一个问题

   TourElement current = getNext();

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

   TourElement current = this;

第二个问题

    return getWaypoint();

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

    return current.getWaypoint();

似乎您的第一次测试也应该失败。我看不到您在createElementList中构建元素的方式,这可能是其通过的原因。