【问题标题】:How can I get an element from linked list with given index in java?java - 如何从具有给定索引的链表中获取元素?
【发布时间】:2019-05-28 14:34:34
【问题描述】:

我正在学习 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());
    }

我不知道原因。请帮我。提前非常感谢你

【问题讨论】:

标签: java linked-list nodes


【解决方案1】:

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

第一个问题

   TourElement current = getNext();

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

   TourElement current = this;

第二个问题

    return getWaypoint();

它总是从头部返回航点。应该是

    return current.getWaypoint();

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

【讨论】:

  • 非常感谢。我虽然第一次 getNext() 将是我列表中的第一个元素。但我是wong。再次感谢您的帮助!!!
  • 乐于助人:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多