博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指 Offer 52. 两个链表的第一个公共节点
阅读量:4034 次
发布时间:2019-05-24

本文共 1643 字,大约阅读时间需要 5 分钟。

题目描述

输入两个链表,找出它们的第一个公共节点。

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3

输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Java

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if( headA==null|| headB==null) return null; int lenA=getLength(headA); int lenB=getLength(headB); ListNode linkLong=headA; ListNode linkedshort=headB; int diff=Math.abs(lenA-lenB); //两个链表的长度查差 if(lenB>lenA){
ListNode temp=linkLong; linkLong=linkedshort; linkedshort=temp; } //长链表先走diff步 for(int i=1;i<=diff;i++){
linkLong=linkLong.next; } //两个链表一起走, 遇到的第一个相同的节点就是所求 while(linkLong!=null && linkedshort!=null&& linkedshort!=linkLong){
linkLong=linkLong.next; linkedshort=linkedshort.next; } return linkLong; //return linkedshort一样 } public int getLength(ListNode head){
int res=0; ListNode cur=head; while(cur!=null){
res++; cur=cur.next; } return res; }}
你可能感兴趣的文章
coursesa课程 Python 3 programming 输出每一行句子的第三个单词
查看>>
coursesa课程 Python 3 programming Dictionary methods 字典的方法
查看>>
Returning a value from a function
查看>>
coursesa课程 Python 3 programming Functions can call other functions 函数调用另一个函数
查看>>
coursesa课程 Python 3 programming The while Statement
查看>>
course_2_assessment_6
查看>>
coursesa课程 Python 3 programming course_2_assessment_7 多参数函数练习题
查看>>
coursesa课程 Python 3 programming course_2_assessment_8 sorted练习题
查看>>
在unity中建立最小的shader(Minimal Shader)
查看>>
1.3 Debugging of Shaders (调试着色器)
查看>>
关于phpcms中模块_tag.class.php中的pc_tag()方法的含义
查看>>
vsftp 配置具有匿名登录也有系统用户登录,系统用户有管理权限,匿名只有下载权限。
查看>>
linux安装usb wifi接收器
查看>>
补充自动屏蔽攻击ip
查看>>
谷歌走了
查看>>
多线程使用随机函数需要注意的一点
查看>>
getpeername,getsockname
查看>>
让我做你的下一行Code
查看>>
浅析:setsockopt()改善程序的健壮性
查看>>
关于对象赋值及返回临时对象过程中的构造与析构
查看>>