【题目描述】
输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
【解题思路】
这道题有一个需要注意的地方就是:凡是两个链表中出现了一样的节点,那么该节点一定是公共节点,往后的一定是一样的。用Python实现的代码如下:
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
list = []
while pHead1:
list.append(pHead1.val)
pHead1 = pHead1.next
while pHead2:
if pHead2.val in list:
return pHead2
else:
pHead2 = pHead2.next