Created
May 20, 2018 03:33
-
-
Save jianminchen/fa27ccd0926f1c7d0872c0009a136b9e to your computer and use it in GitHub Desktop.
how to copy list - iterative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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