leetcode

相交链表

2018-09-07  本文已影响16人  momo1023

相交链表

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

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

注意:

按顺序同时遍历两个链表,若结点相等(此时两个链表等长),则停止。若链表遍历到底,则遍历另外一个链表,直到结点相等(此时,两个链表不等长)。

# 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
        """
        a = headA
        b = headB
        while a != b:
            a = a.next if a else headB
            b = b.next if b else headA
        if a:
            return a
        return None
上一篇下一篇

猜你喜欢

热点阅读