leetcode-- Intersection of Two Linked Lists -- 重点
来源:互联网 发布:nasa 太阳能辐射数据 编辑:程序博客网 时间:2024/06/05 19:23
https://leetcode.com/problems/intersection-of-two-linked-lists/
思路1
http://bookshadow.com/weblog/2014/12/04/leetcode-intersection-two-linked-lists/
判断交点是否存在
如果两个链表有交点,则它们的最后一个节点一定是同一个节点。所以当pA/pB到达链表末尾时,分别记录下A和B的最后一个节点。如果两个链表的末尾节点不一致,说明两个链表没有交点。
思路2
双指针逐步前进,当i到达tail时,继续前进到B链表;当j到达tail时,继续前进到A链表。这样在 i == j时,就是交点。
我的思路:
就是求出两个链表的长度差dif,然后使用双指针指向各自链表的head。对于长一点的链表的指针,我们让其前进dif步,然后双指针一起前进,再判断是否相等。
my code:
class Solution(object): def getIntersectionNode(self, headA, headB): """ :type head1, head1: ListNode :rtype: ListNode """ lenA, i = 0, headA while i: lenA += 1 i = i.next lenB, j = 0, headB while j: lenB += 1 j = j.next flag = 1 if lenA >= lenB else 0 dif = abs(lenA - lenB) i,j = headA, headB if flag: for k in xrange(dif): i = i.next else: for k in xrange(dif): j = j.next while i: if i == j: return i else: i = i.next j = j.next
0 0
- 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
- 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
- Android四大视图动画图文详解
- 旧瓶装新酒的抽象工厂
- 从头到尾彻底理解KMP
- IOS ---设置导航栏
- 逻辑思维
- leetcode-- Intersection of Two Linked Lists -- 重点
- c-简单的计算器
- Market Guide for Cloud Access Security Brokers
- JS之This篇-菜鸟的福利
- Android基础之SharedPreferences
- 随意细解:UI -- 网络编程
- Eclipse的快捷键一览
- 日常学习
- FPGA自学之路1--软件没有USB Blaster选项