剑指offer-两个链表的第一个公共结点(python)

思路一:题目求第一个公共节点,这表明,不止一个公共节点,那么先让一条链表的所有节点入栈,在遍历另一个链表,看看栈中有没有这个元素,有就说明是第一个。
思路二:可以分别让两个链表入栈,(思路就是尾部一定是一样的)。之后分别从栈中pop比较一不一样,找到第一个不一样的后面一个节点就行。
思路三,先比较两个链表,长度,长的先走几个节点,保证两个节点到各自链表尾部的长度是一样的。也不用单独开辟内存空间,一直循环下去就行。

# -*- 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
        if not pHead1 or not pHead2:
            return None
        res1=[]
        res2=[]
        cur1=pHead1
        cur2=pHead2
        while cur1:
            res1.append(cur1.val)
            cur1=cur1.next
        while cur2:
            if cur2.val in res1:
                return cur2
            cur2=cur2.next
        return None

猜你喜欢

转载自blog.csdn.net/qq_42738654/article/details/104432539
今日推荐