LeetCode 160. Intersection of Two Linked Lists
来源:互联网 发布:27岁转行做java 编辑:程序博客网 时间:2024/06/04 17:41
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.
解题思路:分为如下几种情况:
1)两个list中有一个为空,返回null;
2)两个list都不为空,则又分为两种情况:
1)一个list的完全包含了另一个list,也就是说一个list的head在另一个list里
2)一个list与另一个list交叉,各自的head不相交
对于上述两种情况,可以把第一种情况看作是第二种情况的特例,所以主要考虑第二种情况。先计算两个list的节点个数,令较长list的指针先走两个list节点总长的差值,然后再让两个指针同时向前走,判断是否相遇,对于第一种情况,可以在计算list节点个数时,进行判断
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA==null|| headB==null){ return null; }else{ int counta=0,countb=0; ListNode qa=headA,qb=headB; while(qa!=null && qa!=headB){ //headB是headA的一部分 counta++; qa=qa.next; } if(qa!=null){ return headB; } while(qb!=null && qb!=headA){ //headA是headB的一部分 countb++; qb=qb.next; } if(qb!=null){ return headA; } int i=0,counterr=Math.abs(counta-countb); if(counta<countb){ //使qa始终指向较长链表 qa=headB; qb=headA; }else{ qa=headA; qb=headB; } while(i<counterr){ qa=qa.next; i++; } while(qb!=null && qa!=qb){ qa=qa.next; qb=qb.next; } if(qa!=null){ return qa; }else{ 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 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
- jdk spring tomcat 版本冲突
- GitHub版本控制使用(命令行实际操作图解Git使用方法)
- i2c信号的ACK与NACK
- 关于DTW 动态时间规整算法
- 使用java.math.BigDecimal
- LeetCode 160. Intersection of Two Linked Lists
- JAVA笔试、面试基础题目
- 使用WITH AS提高性能简化嵌套SQL
- Intel_IPP 的基本使用方法
- 【Spring系列】——Spring framework简介(一)
- POJ---1703 Find them, Catch them【并查集】
- QML中的Keys事件
- Linux 之始——Ubuntu(16.04)
- C++项目—开发简单图书管理系统