题目描述 输入两个链表,找出它们的第一个公共结点。
代码1:
public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode p1 = pHead1; ListNode p2 = pHead2; while(p1 != p2){ p1 = (p1 == null ? pHead2 : p1.next); p2 = (p2 == null ? pHead1 : p2.next); } return p1; } }代码2:
import java.util.*; public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { ListNode p1 = pHead1; ListNode p2 = pHead2; ArrayList<ListNode> al = new ArrayList<>(); while(p1 != null){ al.add(p1); p1 = p1.next; } while(p2 != null){ if(al.contains(p2)){ return p2; } p2 = p2.next; } return null; } }代码3: