leetcode160相交链表

leetcode160 Intersection of Two Linked Lists

Posted by BY on March 25, 2019

前言

新的一年,好好学习。尝试用python写写代码。

正文

问题来源

本问题来自leetcode上的160题。

问题描述

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

分析:

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

class Solution(object):
    def getListLength(self, head):
        x = 0
        while head:
            x = x + 1
            head = head.next
        return x
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        lenA = self.getListLength(headA)
        lenB = self.getListLength(headB)
        if lenA > lenB:
            l = lenA - lenB
            while l:
                headA = headA.next
                l = l - 1
        else:
            l = lenB - lenA
            while l:
                headB = headB.next
                l = l - 1
        while headA:
            if headA == headB:
                return headA
            headA = headA.next
            headB = headB.next
        return None

总结:

勤思考。

结语

不管怎么样好好加油。