【leetcode】【160】Intersection of Two Linked Lists
来源:互联网 发布:c语言指针视频教程 编辑:程序博客网 时间:2024/06/01 15:07
一、问题描述
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
- If the two linked lists have no intersection at all, return
null
. - 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.
二、问题分析
无非就是遍历两个链表,如果遍历两个链表的指针相同就return。因为两个链表的长度可能不一样,所以有两种方案:①分别计算两个链表的长度,然后遍历②正常遍历,遍历到尾的时候就将指针指向另一个链表,当两个指针同时为空的时候说明同时到尾了。具体的看代码。
三、Java AC代码
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){return null;}ListNode p = headA;ListNode q = headB;int count = 0;while(p!=null || q!=null){if (q == p) {return p;}p = p.next;q = q.next;if(p==null && q==null){ return null;}if (p == null) {count++;p = headB;}if (q == null) {count++;q = headA;}}return null; }
public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null){return null;}ListNode p = headA;ListNode q = headB;int lena = 0;int lenb = 0;while(p!=null){lena++;p = p.next;}while(q!=null){lenb++;q = q.next;}p = headA;q = headB;for(int i=Math.abs(lena-lenb);i>0;i--){if (lena>lenb) {p = p.next;}else {q = q.next;}}while(q!=null&& q!=null){if (p == q) {return p;}else {p = p.next;q = q.next;}}return null; }
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 160Intersection 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
- LINUX服务器的配置
- 汇编语言寻址方式(Linux)
- PHP 面向对面规范 PSR-0 小谈
- XCode 显示代码开发行数
- LEETCODE 66
- 【leetcode】【160】Intersection of Two Linked Lists
- IP数据报首部选项字段详解
- angularjs 路由回退,返回到上一个路由
- iOS APP 逆向安全杂谈之二
- 大型网站架构系列:分布式消息队列
- centos yum源配置问题解决办法
- 欢迎使用CSDN-markdown编辑器
- 杨辉三角的变形
- JavaWeb开发基础--JSP入门