相交链表

2019-12-24  本文已影响0人  二进制的二哈

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-linked-lists

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

如下面的两个链表:


image.png

在节点 c1 开始相交。

示例 1:


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

解法一:

/**
 * 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 aLen = len(headA);
        int bLen = len(headB);
        if(aLen < bLen){
            //A比B短,让B先走几步
            ListNode tmpB = headB;
            int step = bLen - aLen;
            while(step-- != 0){
                tmpB = tmpB.next;
            }
            return func(headA,tmpB);
        }else if(aLen > bLen){
            //A比B长,让A先走几步
            ListNode tmpA = headA;
            int step = aLen - bLen;
            while(step-- != 0){
                tmpA = tmpA.next;
            }
            return func(tmpA,headB);
        }else{
            //两个一样长
            return func(headA,headB);
        }
    }

    private ListNode func(ListNode headA, ListNode headB){
        //两个同等长度的链表,找到相交的节点
        ListNode tmpA = headA;
        ListNode tmpB = headB;
        while(tmpA != null){
            if(tmpA == tmpB)
                return tmpA;
            tmpA = tmpA.next;
            tmpB = tmpB.next;
        }
        return null;
    }

    private int len(ListNode node){
        int len = 0;
        ListNode tmp = node;
        while(tmp != null){
            len++;
            tmp = tmp.next;
        }
        return len;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读