LeetCode160 Question: Write a program for intersecting linked lists to find the starting node where two singly linked lists intersect.

  1. Intersecting linked lists
    Write a program to find the starting node where two singly linked lists intersect.

Such as the following two linked lists:

Insert picture description here

The intersection starts at node c1.

Example 1:

Insert picture description here

输入: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 个节点。
 

Example 2:

Insert picture description here

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

Example 3:

Insert picture description here

输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。
 

note:

If there is no intersection between the two linked lists, null is returned.
After the result is returned, the two linked lists must still maintain the original structure.
It can be assumed that there are no cycles in the entire linked list structure.
The program tries to satisfy O(n) time complexity, and only uses O(1) memory.
Code:

/**
 * 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 p1 = headA;
        ListNode p2 = headB;
        while( p1!= null){
    
    //链表A的长度
            p1 = p1.next;
            lenA++;
        }
        while( p2!= null){
    
    //链表B的长度
            p2 = p2.next;
            lenB++;
        }
        p1 =headA;
        p2 =headB;
        int len = lenA - lenB;//求出长度差
        if(len <= 0){
    
    
            p1 = headB;
            p2 = headA;
            len =lenB-lenA;
        }
        while(len != 0){
    
    
            p1 = p1.next;//较长的链表往后走他们相差的步数
            len--;
        }
        while(p1!=p2){
    
    //一起走
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;//相遇时就是起始节点的位置
    }
}

Guess you like

Origin blog.csdn.net/weixin_44436675/article/details/112691237