Created
September 10, 2015 04:23
-
-
Save montycheese/baf1ded4c36f479aec42 to your computer and use it in GitHub Desktop.
Finds intersecting nodes between two linked lists if any
This file contains hidden or 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
import java.util.HashSet; | |
public class IntersectingNodes { | |
HashSet<NodeCustom> hs = new HashSet<>(); | |
NodeCustom head1; | |
NodeCustom head2; | |
public IntersectingNodes(NodeCustom n1, NodeCustom n2){ | |
this.head1 = n1; | |
this.head2 = n2; | |
} | |
/** | |
* Checks if the LinkedLists share a common node. Returns the node if an intersection is found; | |
* | |
* @return Intersecting node if any between the two linkedlists | |
*/ | |
public NodeCustom solve(){ | |
NodeCustom n = this.head1; | |
hs.add(n); | |
while(n.next != null){ | |
hs.add(n.next); | |
n = n.next; | |
} | |
//look up nodes in 2nd array for duplicates | |
n = this.head2; | |
if(hs.add(n) == false) return n; | |
while(n.next != null){ | |
if(hs.add(n.next) == false){ | |
return n.next; | |
} | |
} | |
// no intersecting nodes found | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment