Day12:剑指 Offer 52. 两个链表的第一个公共节点

题目

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

代码实现

遍历

思路:先遍历两个链表得到各自的长度,然后长的链表先遍历差值次,然后两个链表同时遍历,如果有公共节点一定能得到

/**
 * 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) {
        int lenA = 0;
        int lenB = 0;
        ListNode tempA = headA,tempB = headB;
        while (tempA != null){
            lenA++;
            tempA = tempA.next;
        }
        tempA = headA;
        while (tempB!=null){
            lenB++;
            tempB = tempB.next;
        }
        tempB = headB;
        while (lenA > lenB){
            tempA = tempA.next;
            lenA--;
        }
        while (lenB > lenA){
            tempB = tempB.next;
            lenB--;
        }
        while (tempA!=null){
            if(tempA == tempB){
                return tempA;
            }
            tempA = tempA.next;
            tempB = tempB.next;
        }
        return null;
    }
}

双指针

遍历两个链表,当到链表最后则从另一个链表开始继续遍历,
因为第二次遍历到公共节点的举例相同,最后一定能得到公共节点

/**
 * 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;
        }
        ListNode nodeA = headA;
        ListNode nodeB = headB;
        int n = 0;
        while (nodeA != nodeB && n < 3){
            if (nodeA.next != null) {
                nodeA = nodeA.next ;
            }else {
                nodeA = headB;
                n++;
            }
            if(nodeB.next != null) {
                nodeB = nodeB.next;
            }else {
                nodeB = headA;
                n++;
            }
        }
        return nodeA == nodeB ? nodeA : null;
    }
}

大佬代码

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode A = headA, B = headB;
        while (A != B) {
            A = A != null ? A.next : headB;
            B = B != null ? B.next : headA;
        }
        return A;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值