Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 20, 2018 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/fa27ccd0926f1c7d0872c0009a136b9e to your computer and use it in GitHub Desktop.
Save jianminchen/fa27ccd0926f1c7d0872c0009a136b9e to your computer and use it in GitHub Desktop.
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