腾讯26-相交链表

腾讯26-相交链表leetcode160

编写一个程序,找到两个单链表相交的起始节点。

如下面的两个链表:
在这里插入图片描述
在节点 c1 开始相交。

##先求各自长度
##然后并齐开始走即可,并判断
##误区这里用考虑值相不相等,其实直接考虑结点结构node相等即可

 # Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        ##先求各自长度
        ##然后并齐开始走即可,并判断
        ##误区这里用考虑值相不相等,其实直接考虑结点结构node相等即可
        if headA is None or headB is None:
            return None
        else:
            lena,lenb=1,1
            p1,p2=headA,headB
            while(p1.next):
                lena+=1
                p1=p1.next
            while(p2.next):
                lenb+=1
                p2=p2.next
            if lena>lenb:
                diff=lena-lenb
                while(diff):
                    headA=headA.next
                    diff-=1
            else:
                diff=lenb-lena
                while(diff):
                    headB=headB.next
                    diff-=1
            while(headA):
                if headA!=headB:
                    headA=headA.next
                    headB=headB.next
                else:
                    return headA
            return None
发布了93 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zlb872551601/article/details/103645181
今日推荐