Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
how to copy list - iterative
public static Node copySinglyLinkedListNextOnly(Node root) // 1 -> 2 -> 3 -> 4, return copyRoot value 1
{
// ---
Node newRoot = ;
while( root!= null ){ // 1 //2
newRoot = new Node(root.val);// newroot=1
// new node for next
Node next =null;
if(root.next != null){
next = new Node(root.next.val);
}
newRoot.next = next; // should point new root with value 1 -> node 2
//newRoot.next = root.next;// 1->2 ? new list - should point new root with value 1 -> node 2
root = root.next; // root=2
newRoot = newRoot.next; // newRoot.next -> have not created yet!
--- Julia showed how she solved.
// - - empty list -> one node -> more than one node -> delegate the task
if(root == null) // empty list
return null;
var copyRoot = new Node(root.Value);
var copyChildRoot = copySinglyLinkedListNextOnly(root.Next);
copyRoot.next = copyChildRoot;
return copyRoot; // list only has one node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.