如何在当前链表中复制我的节点?



我很难想出家庭作业的解决方案。我的教授给了我一堆测试链表,并希望我复制链表中存在的每个节点。

例:

int[] array = {1, 2, 3, 4, 10};
LinkedIntList list = new LinkedIntList(array);
list.stutter();

当我打印出新列表时,结果应该是:{1, 1, 2, 2, 3, 3, 4, 4, 10, 10}

这是我到目前为止所拥有的...(我想不出一个合理的while循环(

public void stutter(){
if (front == null) {
return;
}
ListNode current = front;
while (current.next != null) {
if (current != null) {
ListNode duplicate = new ListNode(current.data, current.next);
current.next = duplicate;
} 
current = current.next;
}
}

我也有很多构造函数,但由于我在方法中调用了一个,这里是相关的构造函数:

public ListNode(int data, ListNode next){
this.data = data;
this.next = next;
}

任何帮助不胜感激!!

你只需要确保指向副本的next而不是current.next

public void stutter() {
for (ListNode current = front; current != null; ) {
ListNode duplicate = new ListNode(current.data, current.next);
current.next = duplicate;
current = duplicate.next
}
}

试试这个

public Node reverse(){
Node p= this;
Node firstDuplicate = new Node(p.getItem()); //save reference for first node to return
Node currentDuplicate=firstDuplicate;
while(Node.NIL!=p.getNext()){
Node nextNode = p.getNext();
Node nextCopy = new Node(nextNode.getItem());
currentDuplicate.n = nextCopy;
currentDuplicate = nextCopy;
p = nextNode;
}

/* If the list is empty */
if(firstDuplicate == NIL)
return Node.NIL;
/* If the list has only one node */
if(firstDuplicate.n == Node.NIL)
return firstDuplicate;
// Node reverseRest = new Node(p.getItem(),Node.NIL);
Node rest = new Node(); 
rest = firstDuplicate.getNext();
firstDuplicate.setNext(Node.NIL); 
// Node reverseRest=new Node(p.getItem(),reverseRest);
Node reverseRest=new Node();
reverseRest = rest.reverse();
/* Join the two lists */
rest.setNext(firstDuplicate); 
//p=this;
//  p=p.nthNext(0);
return reverseRest;
}

相关内容

  • 没有找到相关文章

最新更新