题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ // public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if (pHead1 == null || pHead2 == null) { return null; } int one_listNode = ListNodeLenth(pHead1);//5 int two_listNode = ListNodeLenth(pHead2);//4 // 差值 //大于0 说明第一个链表长,让第一个链表先走差值步. //否则 让第二个链表先走差值步. ListNode max_index = null; ListNode min_index = null; if (one_listNode > two_listNode) { max_index = pHead1; min_index = pHead2; } else { max_index = pHead2; min_index = pHead1; } for (int i = 0; i < Math.abs(one_listNode -two_listNode); i++) { max_index = max_index.next; } while (max_index != min_index) { max_index = max_index.next; min_index = min_index.next; } return max_index; } public int ListNodeLenth(ListNode pHead) { if (pHead == null) { return 0; } ListNode temp = pHead; int len = 1; while (temp.next != null) { len++;temp = temp.next; } return len; } }
- 得出长度,之后得出差值。然长的链表先走插值。
- 之后在一起走,就可以找出公共节点。