Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中将链表的大小增加一倍?_Java_Linked List - Fatal编程技术网

如何在java中将链表的大小增加一倍?

如何在java中将链表的大小增加一倍?,java,linked-list,Java,Linked List,例如,给定一个列表,如[1,2,3,4,5]。 在我调用doublelist()之后,原始列表应该是[1,1,2,2,3,3,4,4,5,5] 这是我的密码: public void stutter(){     ListNode curr = front;         while(curr!=null){         ListNode tempNode = new ListNode();         tempNode.data=curr.data; tempNode

例如,给定一个列表,如[1,2,3,4,5]。 在我调用doublelist()之后,原始列表应该是[1,1,2,2,3,3,4,4,5,5]

这是我的密码:

public void stutter(){
    ListNode curr = front;
        while(curr!=null){
        ListNode tempNode = new ListNode();
        tempNode.data=curr.data;
        tempNode.next=curr.next;
        curr.next=tempNode;
        curr=tempNode.next;
    }  
}
我的问题是,如何在不使用tempNode.data=curr.data的情况下编写此方法

ListNode.java

public class ListNode {
    public int data;       // data stored in this node
    public ListNode next;  // a link to the next node in the list

}

您可以在
ListNode

public class ListNode implements Cloneable{
    public int data;       // data stored in this node
    public ListNode next;  // a link to the next node in the list

    @Override
    public ListNode clone()  {
      ListNode cloned = null;
      try {
          cloned = (ListNode) super.clone();
      }finally {
          return cloned;
      }
    }
}

您可以调用
ListNode temp=curr.clone()
以创建新节点

您的计划的实际目的是什么

您可以为
ListNode
创建一个副本构造函数,它可以为您完成一半的工作

class ListNode {
    public int data; // data stored in this node
    public ListNode next; // a link to the next node in the list

    public ListNode() { } //Default constructor. You will need this

    // Create this constructor for ListNode
    public ListNode(ListNode other){
        this.data = other.data;
        this.next = other.next;
    }
}
然后,在你的
口吃
方法中

public void stutter() {
    ListNode curr = front;
    while (curr != null) {
        ListNode tempNode = new ListNode(curr);// Using the copy constructor
        curr.next = tempNode;
        curr = tempNode.next;
    }
}

这有帮助吗?

为什么??这个问题的本质是复制节点,因此您当然要将
.data
从一个节点复制到另一个节点。你想完成什么,为什么?您希望生成的列表是什么样子的(即节点和链接是什么样子的)?如何在不创建的情况下将节点分配给当前节点?。。您需要创建一个节点,这就是通过创建临时节点所做的工作。我如何复制节点?我是java新手。