题解 | 两个链表的第一个公共结点
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
if (pHead1 is None) or (pHead2 is None):
return None
cur1 = pHead1
while (cur1):
cur2 = pHead2
while cur2:
if cur1 == cur2:
return cur1
cur2 = cur2.next
cur1 = cur1.next
return None
循环,外层为pHead1, 内层是pHead2,进行比较是否相等,相等则返回剩余链表,否则指向下一结点,最后若跳出循环,返回空
