编写一个程序,找到两个单链表相交的起始节点。

如下面的链表。
在这里插入图片描述注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
代码:

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45755718/article/details/105212383