public class Test {
private static class Node {
Node next;
private final Integer data;
public Node(Node next, Integer data) {
this.next = next;
this.data = data;
}
}
public static Integer findMergeNode(Node nodeOne, Node nodeTwo) {
Node node2 = nodeTwo;
Node node1 = nodeOne;
Stack<Node> nodeStack1 = new Stack<>(), nodeStack2 = new Stack<>();
while (node2 != null || node1 != null) {
if (node1 != null) {
nodeStack1.push(node1);
node1 = node1.next;
}
if (node2 != null) {
nodeStack2.push(node2);
node2 = node2.next;
}
}
Node resultNode = null;
while (nodeStack1 != null && nodeStack2 != null) {
Node nodeTemp1 = nodeStack1.pop();
Node nodeTemp2 = nodeStack2.pop();
if (!nodeTemp1.data.equals(nodeTemp2.data)) {
break;
}
resultNode = nodeTemp1;
}
if (resultNode == null) {
return null;
}
return resultNode.data;
}
public static void main(String[] args) {
Node node1 = new Node(new Node(new Node(new Node(new Node(new Node(new Node(null, 10), 3), 7), 6), 4), 2), 1);
Node node2 = new Node(new Node(new Node(new Node(new Node(new Node(new Node(null, 10), 4), 3), 4), 5), 6), 10);
System.out.println(findMergeNode(node1, node2));
}
}
评论