【发布时间】: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