Linked list: judge whether a linked list has links and find the intersection of two linked lists

Posted by neave on Mon, 21 Oct 2019 17:56:59 +0200

Problem 1: return the intersection of two linked lists
1. Get the length of two linked lists respectively
2. Get the length difference,
3. Let the head node of the long list go (length difference) first.
4. at this time. The short chain header node is still in place, and the two start to walk together. When the val of the two is equal, the node is the common node, that is, the node that meets.

Question 2: judge whether the linked list has a ring
1. Define two fast and slow pointers. The fast pointer takes two steps first and the slow pointer takes another step. Until the current node of the speed pointer is the same. If the fast pointer is null first, there is no ring and null is returned.
2. If there is a ring, let the starting point and the meeting point start at the same time. Take the same step, and then judge whether it is equal or not. If it is equal, exit the cycle and return to this node.


```public class Solution {
    private int getLength(ListNode head) {
        int len = 0;
        for (ListNode c = head; c != null; c = c.next) {
            len++;
        }

        return len;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = getLength(headA);
        int lenB = getLength(headB);

        ListNode longer = headA;
        ListNode shorter = headB;
        int diff = lenA - lenB;
        if (lenA < lenB) {
            longer = headB;
            shorter = headA;
            diff = lenB - lenA;
        }

        for (int i = 0; i < diff; i++) {
            longer = longer.next;
        }

        while (longer != shorter) {
            longer = longer.next;
            shorter = shorter.next;
        }

        return longer;
    }
}

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;
        // fast encountered null, indicating no ring, returning null
        // fast == slow, indicating meeting point
        do {
            if (fast == null) {
                return null;
            }
            fast = fast.next;
            if (fast == null) {
                return null;
            }
            fast = fast.next;
            slow = slow.next;
        } while (fast != slow);
        // Seeking intersection point
        // If NULL is encountered quickly, it means there is no ring, and null is returned directly.
        // Starting from the meeting point + starting from the starting point, finally meeting
        ListNode p = head;
        ListNode q = slow;
        while (p != q) {
            p = p.next;
            q = q.next;
        }

        return p;
    }
}

Topics: Java