public class Node {
private String data;
private Node next;
public Node(String data, Node next) {
this.data = data;
this.next = next;
}
public String getData() {
return data;
}
public Node next() {
return next;
}
public static void main(String[] args) {
Node z = new Node("z", null);
Node y = new Node("y", z);
Node x = new Node("x", y);
Node b = new Node("b", x);
Node a = new Node("a", b);
Node f = new Node("f", x);
Node e = new Node("e", f);
Node d = new Node("d", e);
String firstCommonValue = Optional.ofNullable(findFirstCommonNode(a, d))
.map(Node::getData)
.orElse("");
System.out.println("第一个公共元素:" + firstCommonValue);
}
private static Node findFirstCommonNode(Node head1, Node head2) {
Set<Node> nodesOfList1 = new HashSet<>();
Set<Node> nodesOfList2 = new HashSet<>();
Node tmp = head1;
while (tmp != null && !nodesOfList1.contains(tmp)) {
nodesOfList1.add(tmp);
tmp = tmp.next();
}
tmp = head2;
while (tmp != null && !nodesOfList2.contains(tmp)) {
if (nodesOfList1.contains(tmp)) {
return tmp;
}
nodesOfList2.add(tmp);
tmp = tmp.next();
}
return null;
}
}
评论