[leetcode]#160. Intersection of Two Linked Lists
来源:互联网 发布:任务管理 知乎 编辑:程序博客网 时间:2024/05/28 06:07
- 题目:写一个程序,找到两个单链表交汇的节点。比如,下面两个单链表交汇节点是c1:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
注意:1,如果两个单链表不交,返回null;2,函数返回后,两个单链表的原始顺序不能改变;3,假定整个结构中没有环;4,你的程序最好以时间复杂度O(n),空间复杂O(1)运行。
- 可以不用计算两个链表的长度,因为本质上我们关心的是让两个链表的指针同时到达交叉点。我们可以定义两个指针,让它们都将两个链表都遍历一遍,那么它们走的总长度是一样的,倘若两个链表相交,那么这两个指针一定会在某个地方相等。
# 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 or not headB: return None p, q = headA, headB while p and q and p != q: p = p.next q = q.next if p == q: return p if not p: p = headB if not q: q = headA return p
阅读全文
0 0
- [LeetCode]160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160.Intersection of Two Linked Lists
- [leetcode] 160.Intersection of Two Linked Lists
- [LeetCode]160. Intersection of Two Linked Lists
- LeetCode--160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- 【LeetCode】160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode *** 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode-160. Intersection of Two Linked Lists
- LeetCode-160.Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- Leetcode 160. Intersection of Two Linked Lists
- LeetCode 160. Intersection of Two Linked Lists
- leetcode 160. Intersection of Two Linked Lists
- 160.[Leetcode]Intersection of Two Linked Lists
- 策略模式
- n元语法
- 页面数据库特殊字符处理
- maven错误
- 单一职责原则
- [leetcode]#160. Intersection of Two Linked Lists
- Grafana+Prometheus打造全方位立体监控系统
- kettle 数据同时插入删除问题
- spring boot实战(第九篇)Application创建源码分析
- IT忍者神龟之Redis 错误1067:进程意外终止,Redis不能启动,Redis启动不了
- 21、TensorFlow 实现单层 Softmax 分类
- 数字图像处理matlab版第六章
- 大富豪3.4端IOS11修复教程
- unicode Entities for Symbols and Greek Letters