[leetCode]剑指 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 = getListLength(headA);
        int lenB = getListLength(headB);
        int lenDif = lenA - lenB;
        ListNode headLong = headA;
        ListNode headShort = headB;
        if(lenDif < 0) {
            headLong = headB;
            headShort = headA;
            lenDif = - lenDif;
        }
        // 先在长链表上走lenDif步
        for(int i = 0; i < lenDif; i++) {
            headLong = headLong.next;
        }
        // 同时在两个链表上遍历
        while( headLong != null && headShort != null) {
            if(headLong == headShort)
                return headLong;
            headLong = headLong.next;
            headShort = headShort.next;
        }
        return null;
    }

    private int getListLength(ListNode head) {
        int count = 0;
        while(head!=null) {
            ++count;
            head = head.next;
        }
        return count;
    }
}

双指针

[leetCode]160.相交链表

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA;
        ListNode pB = headB;
        if(pA == null || pB == null) return null;
        while(pA !=null || pB != null){
            if(pA == null)
                pA = headB;
            else if(pB == null)
                pB = headA;
            if(pA == pB)
                return pA;
            pA = pA.next;
            pB = pB.next;
        }
        return null;
    }
}
posted @ 2020-09-15 10:10  消灭猕猴桃  阅读(62)  评论(0编辑  收藏  举报