gpt4 book ai didi

java - 如何通过在原始列表末尾按顺序重复它们来进行复制以使列表大小加倍

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:38 25 4
gpt4 key购买 nike

我正在尝试找出如何复制下面给出的列表,任何帮助建议都会很好(下面是我的输出)

    public class k {
private ListNode front;

public k() {
front = null;
}

public k(ListNode sentIn) {
front = sentIn;
}
public void duplicate() {
// ListNode head = front;
ListNode temp = front;
while (temp != null && temp.getNext() != null) {
temp = temp.getNext();
}
ListNode head = front;
while (head != null) {
temp.setNext(new ListNode(head.getValue(), temp.getNext()));
head = head.getNext();
}
}

public class ListNode implements Linkable
{
private Comparable listNodeValue;
private ListNode nextListNode;

public ListNode()
{
listNodeValue = null;
nextListNode = null;
}

public ListNode(Comparable value, ListNode next)
{
listNodeValue=value;
nextListNode=next;
}

public Comparable getValue()
{
return listNodeValue;
}

public ListNode getNext()
{
return nextListNode;
}

public void setValue(Comparable value)
{
listNodeValue = value;
}

public void setNext(Linkable next)
{
nextListNode = (ListNode)next;
}
}

我的输出原件:1、5、3、4、7调用重复后:

1, 5, 3, 4, 7, 1, 5, 3, 4, 7, 7, 4, 3, 5, 1

预期输出:1,5,3,4,7,1,5,3,4,7

最佳答案

您在浏览列表时正在修改列表。所以你的循环将继续比你预期的更进一步。即在循环开始时, head 是列表中的第一个, temp 是最后一个。然后你在 temp 后面添加一个 next ,这样当 head 变为 temp (这是列表的末尾)时,它就会有一个 next 。

此外,当您将 temp.getNext() 添加为新 ListNode 中的下一个时,顺序会颠倒过来。

如果您拍摄列表大小的快照并循环多次,它可能会起作用。

public void duplicate(ListNode front) {
//ListNode head = front;
ListNode temp = front;
int size = 0;
while (temp != null && temp.getNext() != null) {
temp = temp.getNext();
size++;
}
ListNode head = front;

while (head != null && size-- >= 0) {
temp.setNext(new ListNode(head.getValue(), null));
temp = temp.getNext();
head = head.getNext();
}
}

关于java - 如何通过在原始列表末尾按顺序重复它们来进行复制以使列表大小加倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53677536/

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