剑指offer 两个链表的第一个公共结点

题目

输入两个链表,找出它们的第一个公共结点。

思路

用两个指针,当它们指向链表末尾时,再从另一个头结点开始遍历。

代码

# -*- 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
        node1 = pHead1; node2 = pHead2
        while node1 != node2:
            node1 = pHead2 if not node1 else node1.next
            node2 = pHead1 if not node2 else node2.next
        return node1

猜你喜欢

转载自blog.csdn.net/y12345678904/article/details/80768346