LeetCode HOT 100 —— 160.相交链表 思路及java代码

39 阅读1分钟

LeetCode HOT 100 —— 160.相交链表

题目

  • image.png
  • 题意即为求两个长度可能不同的链表是否有交点,如果有就返回交点的指针,如果没有则返回null

思路

  1. 求出两个链表的长度,并将两个链表的末端对齐。
    • 因为根据题目测试样例,两个链表头部不相交,中部可能相交
  2. 对齐后对两个链表进行遍历即可

代码

/**
 * 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 curA = headA;
        ListNode curB = headB;
        int lenA = 0, lenB = 0;
        
        // 求两个链表的长度
        while(curA != null) {
            lenA++;
            curA = curA.next;
        }
        while(curB != null) {
            lenB++;
            curB = curB.next;
        }

        // 重置
        curA = headA;
        curB = headB;

        // 确保A链表为最长的链表
        if(lenA < lenB) {
            // 交换lenA
            int tempLen = lenA;
            lenA = lenB;
            lenB = tempLen;
            // 交换头节点
            ListNode tempNode = curA;
            curA = curB;
            curB = tempNode;
        }

        int gap = lenA - lenB;
        // 使两个链表末尾对齐
        while(gap-- > 0) {
            curA = curA.next;
        }

        // 寻找相交点
        while(curA != null) {
            if (curA == curB) 
                return curA;
            curA = curA.next;
            curB = curB.next;
        }
        return null;

    }
}