gpt4 book ai didi

java - 为链表集合创建插入方法 (Java)

转载 作者:行者123 更新时间:2023-11-30 07:28:34 25 4
gpt4 key购买 nike

我正在尝试为视频游戏标题/价格的集合创建自己的链接列表方法。我的添加和删除方法已经取得了一些进展,但我需要创建一个方法来在列表中的某个位置插入一个不只是在末尾的位置。通过使用索引或插入到列表中的其他对象之后。不过,我似乎无法让它发挥作用。

这是我到目前为止所拥有的:

VideoGame.java

public class VideoGame {

private String name;
private Double price;

public VideoGame(String n, Double p)
{
name = n;
price = p;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public Double getPrice()
{
return price;
}

public void setPrice(Double price)
{
this.price = price;
}

@Override
public String toString() {
return "Name: " + name + ", " + "Price: $"+price;
}
}

视频游戏节点

public class VideoGameNode 
{
public VideoGame data;


public VideoGameNode next;


public VideoGameNode(VideoGame s)
{
data = s;
next = null;


}


}

视频游戏列表

public class VideoGameList {
private VideoGameNode list;


public VideoGameList()
{
list = null;

}
//method to add entries into the collection (at the end each time)
public void add(VideoGame s)
{
VideoGameNode node = new VideoGameNode(s);
VideoGameNode current;


if (list == null)
list = node;
else
{
current = list;
while (current.next != null)
current = current.next;
current.next = node;
}
}

我有一个测试程序/驱动程序,但它与我现在需要帮助做的事情无关。我似乎无法让插入方法正常工作。有人有什么想法吗?

最佳答案

您可以创建一个 insert() 方法,该方法也将 position 作为参数。

在此方法中,您可以编写为 add() 方法编写的类似代码。

您只需定义一个 counter 并检查 while 循环内的附加条件,以确定该 counter 是否等于 position 你作为参数传递。如果循环的两个条件中的任何一个得到满足,那么它将终止。

这是代码片段:

public void insert(VideoGame s, int position) {
if (null == list) {
list = new VideoGameNode(s);
} else {
VideoGameNode current = list;
int counter = 0;
while (null != current.next && position > counter++)
current = current.next;
VideoGameNode newNode = new VideoGameNode(s);
newNode.next = current.next;
current.next = newNode;
}
}

关于java - 为链表集合创建插入方法 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com