【发布时间】:2019-10-14 19:32:28
【问题描述】:
我正在尝试编写一个函数以在列表末尾附加一个新元素。但我不知道我的方法如何总是在列表的第一个索引中附加新元素。
我有 2 个名为 Waypoint 和 TourElement 的类。 Waypoint 包含处理链表中点的方法。 TourElment 包含航路点和下一个。
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;
}
//+ method below
}
方法在列表中添加新的TourElement,为什么总是在列表的第一个索引处追加TourElement?
public TourElement append(Waypoint waypoint)
{
TourElement newTourElement = new TourElement();
TourElement current = this;
while(current.next != null)
{
current = current.next;
}
newTourElement.setWaypoint(waypoint);
current.next = newTourElement;
return newTourElement;
}
这是我的测试用例: //创建一个元素列表:
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;
}
//创建一个航点:
private Waypoint createWaypoint(int x, int y) {
Waypoint wp = new Waypoint();
wp.setXY(x, y);
return wp;
}
//添加开始
public TourElement addStart(Waypoint wp) {
TourElement newTourElement = new TourElement();
newTourElement.setWaypoint(wp);
newTourElement.setTourElement(this);
return newTourElement;
}
public void testAppend() {
TourElement elem = createElementList(new int[][] {{2, 2}});
elem = elem.append(createWaypoint(3, 3));
assertArrayEquals(new int[] {2, 2}, elem.getWaypoint().toArray());
assertArrayEquals(new int[] {3, 3}, elem.getNext().getWaypoint().toArray());
assertNull(elem.getNext().getNext());
}
public void testAppend_AfterTwo() {
TourElement elem = createElementList(new int[][] {{1, 1}, {2, 2}});
elem = elem.append(createWaypoint(3, 3));
assertArrayEquals(new int[] {1, 1}, elem.getWaypoint().toArray());
assertArrayEquals(new int[] {2, 2}, elem.getNext().getWaypoint().toArray());
assertArrayEquals(new int[] {3, 3}, elem.getNext().getNext().getWaypoint().toArray());
assertNull(elem.getNext().getNext().getNext());
}
我希望输出如下所示:
测试用例 1:{2,2} => {3,3}
测试用例 2:{1,1} => {2,2} =>{3,3}
但我的实际输出是:
测试用例 1:{3, 3} => {2,2}
测试用例 2:{3,3} =>{1,1} =>{2,2}
【问题讨论】:
-
createElementList是做什么的? -
如@Jonk 所问,请解释
createWaypoint和createElementList方法 -
对不起,我刚刚编辑了我的代码。 createElementList 将创建一个包含很多点的 ElementList。 Waypoint 创建一个点看起来像这样:(1,2)。
标签: java data-structures linked-list append