【LeetCode刷题】160 相交链表 java

题目

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

图示两个链表在节点 c1 开始相交:

示例

【LeetCode刷题】160 相交链表 java_第1张图片

【LeetCode刷题】160 相交链表 java_第2张图片 方法一:先遍历两个链表得到各自长度,然后求出总节点的差值,使长的链表先遍历差值数量的节点数,再A、B一起遍历,如果相等,则返回其节点。

/**
 * 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 countA=0,countB=0;
        ListNode curA=headA,curB=headB;
        while(curA != null){
            curA = curA.next;
            countA++;
        }
        while(curB != null){
            curB = curB.next;
            countB++;
        }
        int index=0;
        if(countA>countB){
            index = countA-countB;
            while(index>0){
                headA = headA.next;
                index--;
            }
        }
        if(countB>countA){
            index = countB-countA;
            while(index>0){
                headB = headB.next;
                index--;
            }
        }
        while(headB!=null){
            if(headA == headB)
                return headA;
            headA = headA.next;
            headB = headB.next;
        }
        return null;

    }
}

 

方法二:可以根据上面的思想,做出很大的优化。其实并不需要计算差值,如果假设A的节点数为a,B的节点数为b,第一个公共节点为node,则node之后的所有节点都是公共节点,数量可以记为c。那么从headA开始遍历,遍历完再遍历B,直至node,此时走了a+(b-c)。同样的,也从headB开始遍历,遍历完后遍历A,直到node,此时也是走了b+(a-c)。

此时,并行的遍历,所走的节点数是一样的,那就有两种情况:遍历了a+b-c个节点后,node为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) {
        ListNode A=headA,B=headB;
        while(A!=B){
            A = A != null ? A.next : headB;
            B = B != null ? B.next : headA;
        }
        return A;

    }
}

你可能感兴趣的:(LeetCode,力扣,刷题,java,leetcode,算法)