leetcode_160. Intersection of Two Linked Lists 找两个单链表的交集的起始位置

题目:

Write a program to find the node at which the intersection of two singly linked lists begins.


For example, the following two linked lists:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

begin to intersect at node c1.


Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory.

题意:

写一个函数找两个单链表交集的起始位置。


代码:

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


class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
      
        if headA == None or headB == None :
            return None
        else :
            nodeA = headA                   #指针1
            nodeB = headB                  #指针2
            
            while nodeA != None and nodeB != None:            #遍历A和B,直到短的链表遍历结束
                nodeA = nodeA.next
                nodeB = nodeB.next
                
            if nodeA == None :               #如果A短,则指针1指向B,直到遍历B结束,找到B-A的差值
                nodeA = headB
                while  nodeA != None and nodeB != None:
                    nodeA = nodeA.next
                    nodeB = nodeB.next
                nodeB = headA                     #同时指针2指向A,两个指针开始同步比较
            else :
                if nodeB == None :        #如果B短,则进行相应的操作
                    nodeB = headA
                    while  nodeA != None and nodeB != None:
                        nodeA = nodeA.next
                        nodeB = nodeB.next
                    nodeA = headB
            
            while  nodeA and nodeA.val != nodeB.val :             #两个链表找到从后开始的相同长度的起始位置后,就开始比较,找出公共部分的起点
                    nodeA = nodeA.next
                    nodeB = nodeB.next
            return nodeA


笔记:

本题用python写的代码,但是并不能AC,因为总是会报:

Submission Result: Memory Limit Exceeded 

用C++写的代码,就能AC


思路:

其实大家思路都差不多,都是计算单链表A和B的长度,然后用长的减去短的,得到差值后,长的单链表先走,经过计算得到的差值的节点后,两个单链表开始比较,寻找交集的起始节点。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值