leetcode之Intersection of Two Linked Lists
来源:互联网 发布:diy手机墙纸软件 编辑:程序博客网 时间:2024/05/14 02:26
这道题据说是个经典题啦,可惜我这种半路出身的一开始还真是没想到。解题思路是先算出来2个列表的长度,相减就是长的多出来的部分。然后切掉,然后2边一起开始走,如果是有连接点,则一定能相遇,否则走到尾没相遇的话就返回None。代码如下:
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ if not headA: return None if not headB: return None lenofheadA = 0 lenofheadB = 0 headB1 = headB headA1 = headA while headB1: lenofheadB += 1 headB1 = headB1.next while headA1: lenofheadA += 1 headA1 = headA1.next deviation = abs(lenofheadA - lenofheadB) if lenofheadA >= lenofheadB: for i in range(deviation): headA = headA.next NumofStep = 0 while NumofStep < lenofheadB: if headA == headB: return headB else: headB = headB.next headA = headA.next NumofStep += 1 else: return None else: for i in range(deviation): headB = headB.next NumofStep = 0 while True: if headA == headB: return headB else: headB = headB.next headA = headA.next NumofStep += 1 else: return None
0 0
- leetcode之Intersection of Two Linked Lists
- LeetCode之Intersection of Two Linked Lists
- LeetCode 之 Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- Leetcode之Intersection of Two Linked Lists
- leetcode之Intersection of Two Linked Lists
- Leetcode 之 Intersection of Two Linked Lists
- [leetcode] [leetcode]Intersection of Two Linked Lists
- 【LeetCode】Intersection of Two Linked Lists
- LeetCode: Intersection of Two Linked Lists
- [Leetcode] Intersection of Two Linked Lists
- [Leetcode]Intersection of Two Linked Lists
- LeetCode:Intersection of Two Linked Lists
- leetcode: Intersection of Two Linked Lists
- Leetcode: Intersection of Two Linked Lists
- Intersection of Two Linked Lists--leetcode
- [leetcode]Intersection of Two Linked Lists
- 使用国内镜像源来加速python pypi包的安装
- 嵌入式linux中YUV转换成RGB算法
- Android窗口抖动之动画实现
- pig安装和使用
- 同学大神写的很棒的C/C++的Matrix库函数~~力荐
- leetcode之Intersection of Two Linked Lists
- C++灵巧计数器技术
- 事务的原子性
- 基础回顾之DateFormater
- The Apache Tomcat Connectors - AJP Protocol Reference
- java中int和integer,String,StringBuffer,StringBuilder的区别
- mongodb 基于地理位置的查询
- HTTP协议小结
- 网站绑定域名后不能用IP直接访问了?