第八周作业
时间复杂度:O(m+n),空间复杂度O(m+n)
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;
}
评论