[勇者闯LeetCode] 160. Intersection of Two Linked Lists
来源:互联网 发布:德国公开赛 知乎 编辑:程序博客网 时间:2024/06/05 19:07
[勇者闯LeetCode] 160. Intersection of Two Linked Lists
Description
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked list
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
Notes:
If the two linked lists have no intersection at all, returnnull
.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
Information
- Tags: Linked List
- Difficulty: Easy
Solution
两个指针分别从两个链表的头部开始扫描,到达尾部后跳到另一个链表的头部继续扫描,则扫描过程中两个指针相遇的点即为两个链表开始相交的点。
Python Code
# 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 """ currA, currB = headA,headB begin, tailA, tailB = None, None, None while currA and currB: if currA == currB: begin = currA break if currA.next: currA = currA.next elif tailA is None: tailA = currA currA = headB else: break if currB.next: currB = currB.next elif tailB is None: tailB = currB currB = headA else: break return begin
阅读全文
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
- leetcode 160. Intersection of Two Linked Lists
- 【Java8源码分析】并发包-AtomicInteger
- Web应用的组件化开发(二)
- C#中精确计时的一点收获
- java实现定时任务的三种方法
- 二进制,十进制,八进制,十六进制的相互装换
- [勇者闯LeetCode] 160. Intersection of Two Linked Lists
- Linux常用命令
- unit4-SMTP配置
- C++学习笔记9:字符串和string类简介
- Unity 检查支持的.NET版本
- HDU
- MySQL5.7的复制(一补充)
- 把信息保存在html文件中的代码
- HDU