lc 相交链表
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
代码:
# 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 is None or headB is None: return None curA = headA print type(headA) curB = headB len_a = 0 len_b = 0 while curA is not None: len_a += 1 curA = curA.next while curB is not None: len_b += 1 curB = curB.next curA = headA curB = headB minus = len_a - len_b print minus if minus >= 0: while curA is not None and minus > 0: curA = curA.next minus -= 1 else: while curB is not None and minus < 0: curB = curB.next minus += 1 while curA is not None and curB is not None and curA != curB: curA = curA.next curB = curB.next if curA is None: return None else: return curA
思路:短的链表先走长链表与短链表之差,然后再一起走,返回交点
posted on 2020-05-25 00:53 FriskyPuppy 阅读(128) 评论(0) 编辑 收藏 举报