输入两个链表,找出它们的第一个公共结点。
1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 class Solution: 7 def FindFirstCommonNode(self, pHead1, pHead2): 8 l1 = pHead1 9 l2 = pHead2 10 while l1 != l2: 11 l1 = pHead2 if l1 == None else l1.next 12 l2 = pHead1 if l2 == None else l2.next 13 return l1 14 # write code here
Java版代码,leetcode地址:
1 public class Solution { 2 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { 3 ListNode l1 = headA; 4 ListNode l2 = headB; 5 while (l1 != l2) { 6 if (l1 == null) { 7 l1 = headA; 8 } else { 9 l1 = l1.next; 10 } 11 12 if (l2 == null) { 13 l2 = headB; 14 } else { 15 l2 = l2.next; 16 } 17 } 18 return l1; 19 } 20 }