import java.util.*; public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { Stack<ListNode> s1=new Stack<>(); Stack<ListNode> s2=new Stack<>(); while (pHead1 != null){ s1.push(pHead1); pHead1=pHead1.next; } while (pHead2 != null){ s2.push(pHead2); pHead2=pHead2.next; } ListNode result=null; while (!s1.isEmpty() && !s2.isEmpty() && s1.peek() ==s2.peek()){ s1.pop(); result =s2.pop(); } return result; } }
方法2:用两个指针同时往后走 最终两个指针到达相同的结点或者同时到达null
如果两个数组长度相同 第一遍直接找到或者找不到;
如果两个数组长度不相同 第一遍结束的时候两个pHead会在同一位置开始往后找 相当于长度相同的数组
import java.util.*; public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { if(pHead1 == null || pHead2 == null){ return null; } ListNode l1=pHead1,l2=pHead2; while(pHead1 != pHead2){ if(pHead1 != null) pHead1 = pHead1.next; else pHead1=l1; if(pHead2 != null) pHead2 = pHead2.next; else pHead2=l2; } return pHead1; } }
原文:https://www.cnblogs.com/nlw-blog/p/12443658.html