private static Node findFirstCommonNode(Node pHead1, Node pHead2) {
if (pHead1 == null || pHead2 == null) { return null; } Deque<Node> pStack1 = new ArrayDeque<>(); Deque<Node> pStack2 = new ArrayDeque<>(); // 将元素存入栈中 System.out.println("第一个链表元素为: "); while (pHead1 != null) { pStack1.push(pHead1); System.out.print(pHead1.value + " "); pHead1 = pHead1.next; }
System.out.println("\n第二个链表元素为: "); while (pHead2 != null) { pStack2.push(pHead2); System.out.print(pHead2.value + " "); pHead2 = pHead2.next; }
// 从后往前查找第一个合并元素 Node temp = null; while (!pStack1.isEmpty() && !pStack2.isEmpty()) { Node pH1 = pStack1.pop(); Node pH2 = pStack2.pop(); if (pH1.value.equals(pH2.value)) { temp = pH1; } else { break; } } return temp; }
评论