Niuke.com High-Frequency Algorithm Questions Series-BM10-The First Common Node of Two Linked Lists
Topic description
Input two acyclic singly linked lists, find their first common node, and return empty if there is no common node. (Note that because the incoming data is a linked list, the prompt of the wrong test data is displayed in other ways to ensure that the incoming data is correct)
See the original title: BM10 The first common node of two linked lists
Solution 1: Double loop
Using double loop to traverse 2 linked lists is simple and rude, but slightly less efficient.
Solution 2: Double pointer method
Use two pointers l1 and l2 to traverse from the head node of linked list 1 and linked list 2 respectively. After traversing to the end, traverse from linked list 2 and linked list 1 respectively. If the two linked lists have a common intersection, then l1 and l2 will definitely be in Meet at the intersection, otherwise, l1 and l2 are null after traversing the two linked lists respectively, and there is no common node.
code
public class Bm010 {
/**
* 方法一:双重循环
*
* @param pHead1 链表一
* @param pHead2 链表二
* @return
*/
public static ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
ListNode node1 = pHead1;
// 外层循环遍历链表一的结点
while (node1 != null) {
ListNode node2 = pHead2;
// 内层循环遍历链表二的结点
while (node2 != null) {
if (node2 == node1) {
return node1;
}
node2 = node2.next;
}
node1 = node1.next;
}
return null;
}
/**
* 双指针法
*
* @param pHead1
* @param pHead2
* @return
*/
public static ListNode findFirstCommonNode2(ListNode pHead1, ListNode pHead2) {
// l1和l2分别从链表一和链表二的头结点遍历,遍历到尾部后,再分别从链表二和链表一遍历
ListNode l1 = pHead1, l2 = pHead2;
while (l1 != l2) {
l1 = (l1 == null) ? pHead2 : l1.next;
l2 = (l2 == null) ? pHead1 : l2.next;
}
// 如果两个链表有公共交点,则l1和l2一定会在交点处相遇,此时l1就是公共结点
// 否则,l1和l2分别遍历完两个链表后都是null,没有公共结点,返回null
return l1;
}
public static void main(String[] args) {
ListNode pHead1 = ListNode.testCase2();
System.out.println("链表一为");
ListNode.print(pHead1);
ListNode pHead2 = ListNode.testCase1();
pHead2.next.next.next = pHead1.next.next;
System.out.println("链表二为");
ListNode.print(pHead2);
ListNode.print(findFirstCommonNode(pHead1, pHead2));
ListNode.print(findFirstCommonNode2(pHead1, pHead2));
}
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。