gpt4 book ai didi

java - LinkedList深拷贝java

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

我试图对名为 DictionaryNode 的链接列表进行深层复制,但我无法在显示方法中显示它的内容,因为它始终为空。为什么 DictinaryNode temp 总是 null ?如果我尝试分配 temp = head 工作,但使用 temp = copy 则不会。

public class ListOfNodes {

public class DictionaryNode {
protected String word;
private int level;
private DictionaryNode next;
private int space = 0;

public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
System.out.println(temp.word)
temp = temp.next;
}
}


public DictionaryNode( String word, int level ) {
this.word = word;
this.level = level;
next = null;
}
}

private DictionaryNode head = null;
public DictionaryNode copy = null;

//used to do deep copy
public void Clone() {
DictionaryNode temp = head.next;

while( temp != null ) {
copy = new DictionaryNode( temp.word , temp.level );
copy = copy.next;
temp = temp.next;
}
}

public void displayCopy() {
DictionaryNode temp = copy.next;
while( temp != null ) {
Sytem.out.println(temp.word)
temp = temp.next;
}
}

最佳答案

该程序将演示如何对列表进行深层复制。它比您的具体示例更通用,因此希望它对其他人也有帮助。

public class Java_Practice {

private static class LinkedListTest {

private String data;
private LinkedListTest next;

public LinkedListTest(String data) {
super();
this.data = data;
}

public String getData() {
return data;
}

public LinkedListTest getNext() {
return next;
}

public void setNext(LinkedListTest next) {
this.next = next;
}

@Override
public String toString() {
return "LinkedListTest [data=" + data + ", next=" + next + "]";
}

}

// Do a deep copy
private static LinkedListTest copyLlt(LinkedListTest original) {

LinkedListTest copy = new LinkedListTest(original.getData() + " copied");

LinkedListTest nextCopy = original.getNext();
LinkedListTest current = copy;

while (nextCopy != null) {

LinkedListTest newCopy = new LinkedListTest(nextCopy.getData() + " copied");
newCopy.setNext(nextCopy.getNext());

current.setNext(newCopy);

current = newCopy;
nextCopy = newCopy.getNext();
}

return copy;
}

public static void main(String[] args) {

LinkedListTest firstLlt = new LinkedListTest("First");
LinkedListTest secondLlt = new LinkedListTest("Second");
LinkedListTest thirdLlt = new LinkedListTest("Thrid");

firstLlt.setNext(secondLlt);
secondLlt.setNext(thirdLlt);

LinkedListTest copiedLlt = copyLlt(firstLlt);

// Data should say First, Second, Third
System.out.println("Original LinkedListTest: " + firstLlt.toString());

// Data should say First Copied, Second Copied, Third Copied
System.out.println("Copied LinkedListTest: " + copiedLlt.toString());
}

}

关于java - LinkedList深拷贝java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39930578/

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