gpt4 book ai didi

java - 链表添加节点不起作用

转载 作者:行者123 更新时间:2023-12-01 07:35:07 24 4
gpt4 key购买 nike

我正在尝试创建一个方法,将节点添加到我的链接列表中。该方法采用一个 int (用于指定新链接应该去的位置)和 String (因为我的链接列表包含字符串)。我编写了一些代码,我认为会在列表中的特定点添加链接,但是当我在添加新节点后打印列表时,我发现新节点尚未添加。我很惊讶,因为我在编写代码时很小心地测试了代码的行为,并且 add 方法似乎达到了我的预期——但是新打印的列表没有反射(reflect)添加新链接后的更改。谁能告诉我哪里出错了:/

ps:类和方法的名称没有争议,是我的老师选择的,这就是它们必须保留的方式。

谢谢!

测试链表

class LinkedListTest 
{
public static void main(String[] args)
{
LinkedList list = new LinkedList();

list.insertFirst("cat");
list.insertFirst("dog");
list.insertFirst("fish");
list.insertFirst("cow");
list.insertFirst("horse");
list.insertFirst("pig");
list.insertFirst("chicken");

list.add(3, "mouse");

list.print();
}
}

链表类

public class LinkedList 
{
private Link first;

public LinkedList()
{
first = null;
}

public void insertFirst(String word)
{
Link link = new Link(word);
link.next = first;
first = link;

System.out.print(first.item + " ");
}

public String deleteFirst()
{
Link temp = first;
first = first.next;
return temp.item;
}

public String get(int index)
{
Link current = first;
while (index > 0)
{
index--;
current = current.next;
}

return current.item;
}

public void add(int index , String someString)
{

Link current = first;

while (index>0)
{
index--;
current = current.next;
}

Link newLink = new Link(someString);
newLink.next = current;
current = newLink;

}

public void print()
{
System.out.println("-----------PRINTING LIST------------");
Link current = first;
while(!(current==null))
{
System.out.println(current.item);
current = current.next;
}
}
}

链接类

public class Link 
{
public String item;
public Link next;

public Link(String theItem)
{
item = theItem;
}
}

最佳答案

当插入到这样的列表中时。您将必须设置两个“下一个”链接。下一个指向您要插入的项目,下一个指向您要插入的项目,指向您正在滑过的项目。

希望这有帮助。

关于java - 链表添加节点不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13093185/

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